views:

910

answers:

6

How could I, on the fly, remove spaces entered into a textbox while the person is typing?

A: 

on the fly? Perhaps on every keypress event, take the string in the textbox

$('#id').val($.trim($('#id').val());

This will remove any extraneous spaces in front and back.

Dhana
A: 

I use following code:

<input type="text" onkeyup="fixme(this)" onblur="fixme(this)"/>

function fixme(element) {
 var val = element.value;
 var pattern = new RegExp('[ ]+', 'g');
 val = val.replace(pattern, '');
 element.value = val;
}

the regexp line contains what i want replaced... i have for number only fields:

var pattern = new RegExp('[^0-9]+', 'g');
Niko
Right-click paste?
Josh Stodola
add it on the onblur as well
Niko
-1 for obtrusiveness
Justin Johnson
A: 

You could try it like this:

$("input").keypress(function (e) {
   $(this).val($(this).val().replace(' ',''));
}
Raúl Roa
No need to waste performance, wrapping "this" in a jQuery object. We are after all talking about inputs. Both a textarea and an input has got the .value property.
roosteronacid
+14  A: 
$(function() {
  var txt = $("#myTextbox");
  var func = function() {
    txt.val(txt.val().replace(/\s/g, ''));
  }
  txt.keyup(func).blur(func);
});

You have to additionally handle the blur event because user could use context menu to paste ;)

Josh Stodola
Regular expressions are slow. Handling the blur-event is not needed if you bind your logic to the keyup-event.
roosteronacid
Belay that. The blur event is a smart move :)
roosteronacid
+1 for getting the blur part. missed that in my answer.
seth
@roosteronacid the speed of regular expressions in this case is inconsequential.
Justin Johnson
+1 for being the only one to consider all whitespace
Justin Johnson
I'm all for the whole "do not pre-optimize". But if it can be done faster, why not do so? :) -- (faster == cleaner, in my head anyways).
roosteronacid
Faster? You can't be serious. If you really think your backwards loop is going to blow my mini RegEx out of the water in performance, than I would consider your username to be precise.
Josh Stodola
do I add this to my $(document).ready(); function or outside of that?
mrblah
I didn't say your code will blow up--it's neat and tidy, and I like it. I guess it's just a matter of opinion. When it comes to JavaScript, I like to create code that runs as fast as possible. Considering that this is a knowledgebase for novice -as well as experienced programmers, why not try to dish out some best-practices while your at it?
roosteronacid
@homestead: $(document).ready(function () { ... }) creates a closure. If you add Josh's code inside of that, you can only access it inside that closure. This way you avoid polluting the global namespace as well. If you are only gonna use this functionality in one interface, I'd suggest you put it inside $(document).ready( ... );
roosteronacid
@roosteronacid It's not a matter of opinion, the regexp is faster than your code. See my answer.
Justin Johnson
ok it worked. Have you guys seen twitter's implementation? A space can never be entered at all! see the username field: https://twitter.com/signup
mrblah
+6  A: 

This ridiculousness about regular expressions being slow/bad for this task needs to be put the the test. This may not be the most accurate benchmark, but it will do to illustrate my point.

// Modified roosteronacid's example to consider all whitespace characters
function sanitizer(s) {
    var a = s.split(""),
        i = a.length,
        r = "";

    while (i) {
        i--;
        if (a[i] !== " " || a[i] !== "\t" || a[i] !== "\r" || a[i] !== "\n" || a[i] !== "\f" || a[i] !== "\v") {
            r += a[i];
        }
    }

    return r;
}

// Regular expression method wrapped in a function to incur the same overhead
function regexp(s) {
  return s.replace(/\s+/g, '');
}

var iterations = 10000;
// 1024 characters or good meausure
var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris luctus tristique ante, ac suscipit tortor consequat at. Fusce id tortor quis felis faucibus dignissim. Pellentesque viverra pellentesque eros, ac sagittis quam cursus a. Nullam commodo mauris eget nisi luctus vitae ultricies leo volutpat. Morbi quis quam id elit accumsan semper. Praesent aliquam aliquam tortor vel vulputate. Nulla adipiscing ipsum vitae est luctus imperdiet. Suspendisse potenti. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus at urna ut leo ornare commodo. Quisque eros dolor, adipiscing quis malesuada quis, molestie nec lectus. Quisque et odio nibh. Integer mattis tincidunt ligula, eu scelerisque erat posuere non. Sed ipsum quam, fringilla id porttitor ac, placerat quis nunc. Praesent sodales euismod ultricies. In porta magna metus. Morbi risus risus, hendrerit sit amet ultrices eu, interdum placerat massa. Nunc at leo dui. Morbi eu nunc mi, at ullamcorper felis. Duis et metus metus. ";

var s = new Date();
for ( var i=0; i<iterations; ++i ) {
  sanitizer(text);
}

console.log((new Date()).getTime() - s.getTime());

var s = new Date();
for ( var i=0; i<iterations; ++i ) {
  regexp(text);
}

console.log((new Date()).getTime() - s.getTime());

Results of 8 executions:

# Initial times
sanitizer: 5137, 8927, 8817, 5136, 8927, 5132, 8807, 8804
regexp:    1275, 1271, 1480, 1278, 1274, 1308, 1270, 1270

# Dropped highest and lowest values
sanitizer: 5137, 8817, 5136, 8927, 8807, 8804
regexp:    1275, 1271, 1278, 1274, 1308, 1270

# Averages
sanitizer: (5137 + 8817 + 5136 + 8927 + 8807 + 8804) / 6 = 7604.66667
regexp:    (1275 + 1271 + 1278 + 1274 + 1308 + 1270) / 6 = 1279.33333

Turns out using regular expressions is 594% faster.

See Josh Stodola answer for the implementation.

Edit: I notice that roosteronacid's method has changed; however, using r as an array makes it even slower.

Justin Johnson
well put. Was going to do the same thing. (I added a link to your answer. Hope you don't mind.)
seth
Thanks, not a problem.
Justin Johnson
One possible explanation is that the regexp implementation has been carefully optimised. Another great example of using a standard library (or in this case language feature) rather than rolling your own.
Tom Leys
That's highly likely. I haven't seen any comparisons lately between JavaScript native code and interpreted code, but we'd likely see similar results.
Justin Johnson
+1 for doing the benchmarks. I was going to do this, but did not have the time. Whats-his-name *needed* to see this answer!
Josh Stodola
I stand corrected.
roosteronacid
A: 

@Justin Johnson: What browser version or javascript engine were your (sept 09) benchmarking results derived from?

johndoe