Prevent typing spaces in an HTML text box with jQu

2019-03-11 07:27发布

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?

2条回答
够拽才男人
2楼-- · 2019-03-11 08:28

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-11 08:33

Try use keyup

Live Demo

$('input').keyup(function() {
    str = $(this).val();
    str = str.replace(/\s/g,'');
    $(this).val(str);
});
查看更多
登录 后发表回答