Prevent typing whitespace / disable spacebar in input - Javascript

How can I prevent typing of the whitespace character in input textbox by javascript function ?
posted on 26.01.2020 at 16:37
0pnshow more
To prevent typing whitespace in input field or textarea by using javascript, You can use this solution:

<script type="text/javascript">

function keyPressed(){
var key = event.keyCode || event.charCode || event.which ;
return key;


<input type="text" onKeyDown="javascript: var keycode = keyPressed(event); if(keycode==32){ return false; }" />

When a key is pressed, the function will get the keycode. The condition will check the keycode and if the spacebar is pressed it will return false. This will "disable" spacebar in input field or textarea.
posted on 01.02.2020 at 15:28
0pnshow more
share on facebookshare on twitter
2021 AnswerTabsTermsContact us