Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent typing spaces in an HTML text box with jQuery

So I've got an HTML form that users can type in. How can I use javascript/jQuery to immediately and seamlessly remove spaces from a text box when one is put in? I've been researching the .val() jQuery method and came up with this:

$('input').keydown(function() {
    str = $(this).val();
    str = str.replace(/\s/g,'');
    $(this).val(str);
});

That does weird things to removing text and the spaces still show up on keystroke, they just get removed on the following keystroke. Any suggestions?

like image 730
alt Avatar asked Jun 29 '12 20:06

alt


2 Answers

You could prevent it from being added at all by checking whether the key pressed is the space bar and returning false if so:

​$("input").on("keydown", function (e) {
    return e.which !== 32;
});​​​​​

Here's a working example.

like image 56
James Allardice Avatar answered Nov 15 '22 20:11

James Allardice


Try use keyup

Live Demo

$('input').keyup(function() {
    str = $(this).val();
    str = str.replace(/\s/g,'');
    $(this).val(str);
});
like image 21
Adil Avatar answered Nov 15 '22 20:11

Adil