Disable spaces on input not working for devices

Viewed 309

I'm trying to disable spaces on keydown, is working fine on desktop browsers but not working on devices like android.

In Javascript I use next script:

function noSpaces(e) {
    return e.which === 32 ? false : true;
}

And on HTML I use:

<input type="text" onkeydown="return noSpaces(event)" />

Any idea why is not working on devices?

1 Answers

Virtual keyboard on mobile devices may give an unexpected value for Event.which, in many cases it will return value 229 (reference caniuse keyboardevent-which).
Event.which is also deprecated. So what you should do is to use the more standard Event.key. Note that Event.key isn't based on code-number (like 32, 33, 34,...), you must use correct value (see more at MDN KeyboardEvent.key).
So your example should be corrected into something like this: e.key === " "

Related