Possible Duplicate:
See if Input Has Spaces with jQuery
I have this code for no spaces. Well atleast I thought it was for no spaces in username in registration…Now looking at it it is for every single key up! Can someone help me to make it spaces only?
(function($){
$(function(){
$('#username_reg').keyup(function(){
str = $(this).val(),
str = str.replace(/\s/g,''),
$(this).val(str),
alert('No space are allowed in usernames');
});
});
})(jQuery);
I tried this code as well just now, did not work :/
$("input#username_reg").on("keydown", function (e) {
return e.which !== 32;
});
I believe the following code will do what you want:
That is, on keyup, if the key was a space display the alert with the message and remove the space. But also, on blur remove any spaces that might be in the field – because the user may copy/paste or drag’n’drop without using the keyboard.
Demo: http://jsfiddle.net/wP8mP/
EDIT: If it were my code I would probably remove the alert altogether – I’d just prevent spaces being typing by calling
event.preventDefault()on key down, and still remove spaces on blur in case of a copy/paste.Demo: http://jsfiddle.net/wP8mP/1/