Skip to content
Advertisement

Prevent typing non-numeric in input type number

Using <input type=number> will cause this.value inside of an event listener to return an empty string if the input is not a valid number. You can see an example of this at http://jsfiddle.net/fSy53/

However, the invalid characters are still displayed in the input.

Is there any way to get the value that is actually displayed, including the invalid characters, from within an event listener?

My ultimate goal is to prevent users from actually typing any non-numeric characters into the field. I need to use type=number so that the numeric virtual keyboard is used by mobile devices. My goal would be to do something like this.value = this.value.replace(/[^0-9.]/g, "") on keyup keypress, but this doesn’t work because if an invalid character is typed, reading from this.value returns "".

Advertisement

Answer

Try preventing the default behaviour if you don’t like the incoming key value:

document.querySelector("input").addEventListener("keypress", function (evt) {
    if (evt.which < 48 || evt.which > 57)
    {
        evt.preventDefault();
    }
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement