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?
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.
Try use keyup
Live Demo
$('input').keyup(function() {
str = $(this).val();
str = str.replace(/\s/g,'');
$(this).val(str);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With