console.log
console.log

Reputation: 123

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?

Upvotes: 2

Views: 3134

Answers (2)

Hackerman
Hackerman

Reputation: 12305

How about something like this:

document.getElementById("pwd").addEventListener('keydown', function (event)
{
    // if the keyCode is 32 ( space key was pressed )
    if (event.keyCode === 32) {
        // prevent default behaviour
        event.preventDefault();
        return false;
    }
});

Working fiddle: https://jsfiddle.net/a7yprnjd/

Upvotes: 2

TimoStaudinger
TimoStaudinger

Reputation: 42460

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)" />

Upvotes: 4

Related Questions