Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "".

like image 308
Explosion Pills Avatar asked Nov 13 '13 23:11

Explosion Pills


People also ask

How do you stop typing in input type number?

If you are able/allowed to use jQuery, you can disable keypress on the type='number' . $("[type='number']"). keypress(function (evt) { evt. preventDefault(); });

How do I make input type text only accept numbers?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do you make input fields only numeric?

You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.

How do you prevent a zero as the first character when typing in input type number?

keypress(function(evt) { if (evt. which == "0".


2 Answers

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();     } }); 
like image 182
Glenn Lane Avatar answered Sep 20 '22 18:09

Glenn Lane


You can accomplish this by preventing the keyPress event from occurring for non-numeric values

e.g (using jQuery)

$('.input-selector').on('keypress', function(e){   return e.metaKey || // cmd/ctrl     e.which <= 0 || // arrow keys     e.which == 8 || // delete key     /[0-9]/.test(String.fromCharCode(e.which)); // numbers }) 

This accounts for all different types of input (e.g. input from the number pad has different codes than the keyboard) as well as backspace, arrow keys, control/cmd + r to reload etc

like image 30
dlangevin Avatar answered Sep 22 '22 18:09

dlangevin