MC23 MC23 - 2 months ago 11
Javascript Question

How to make JavaScript block the 'space key' inside a textbox

First of all, I've already tried this solution and it doesn't work for me, unless I put the script in the HTML page (I didn't do it because I've a page for all the scripts). Another solution that does work but that I haven't understand is this:

<input type="password" id="pwd" required pattern=".{8,16}" title="8 characters minimun, 16 characters maximum" name="fpwd" placeholder="Password" size = "13" onkeypress="return (event.keyCode != 32&&event.which!=32)>

So, the question is: why the first solution works only if the script is in the HTML page?


The onkeypress event handler is executed every time the user enters a character into the text field.

The entered character's key code is stored in the event's keyCode or which parameter depending on the environment (browser).

If the character code equals the key code for SPACE (32), the event handler returns false, which causes the browser to dismiss the event, i.e. prevents it from adding the typed character to the input field.

Type in this snippet to see the different key codes:

<input onkeypress="return console.log(event.keyCode || event.which), (event.keyCode != 32 && event.which != 32)" />