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 ""
.
If you are able/allowed to use jQuery, you can disable keypress on the type='number' . $("[type='number']"). keypress(function (evt) { evt. preventDefault(); });
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.
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.
keypress(function(evt) { if (evt. which == "0".
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(); } });
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With