How prevent whitespace in input field with plain javascript
Use event.preventDefault to prevent its default behavior.
var field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var key = event.keyCode;
if (key === 32) {
event.preventDefault();
}
});
<input type="text" name="username" />
If you want to use the return false;
, then you should use the onkeypress
of the input instead, jsfiddle
field.onkeypress = function(e) {
var key = e.keyCode;
return (key !== 32);
};
Try checking for all the different kinds of whitespaces listed here Are there other whitespace codes like   for half-spaces, em-spaces, en-spaces etc useful in HTML?
So you code would be:
var field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var
key = event.keyCode;
return (key !== 32 && key !== 160 && key != 5760 && key != 8192 && key != 8192 && key != 8194 && key != 8195 && key != 8196 && key != 8197 && key != 8198 && key != 8199 && key != 8200 && key != 8201 && key != 8202 && key != 8232 && key != 8233 && key != 8239 && key != 8287 && key != 12288);
});
Here is the complete list of all the different kinds of whitespaces: https://en.wikipedia.org/wiki/Whitespace_character#Spaces_in_Unicode
Modify the input like:
<input type="text" name="username" onkeypress="CheckSpace(event)"/>
Then the javascript is:
<script type="text/javascript">
function CheckSpace(event)
{
if(event.which ==32)
{
event.preventDefault();
return false;
}
}