I need to make sure that a certain <input>
field only takes numbers as value. The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.
Is there a neat way to achieve this?
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.
To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field. After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”
Firstly, create an array that stores all the ASCII codes or values of the digits 0 (ASCII value 48) through 9 (ASCII value 57) so that the input in the textbox can be validated later on. Next, set the max length of the input to 10 using maxlength attribute of the input tag.
You can use HTML5 input type number to restrict only number entries:
<input type="number" name="someid" />
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>
See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.
Update: There is a new and very simple solution for this:
It allows you to use any kind of input filter on a text
<input>
, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.
See this answer or try it yourself on JSFiddle.
For general purpose, you can have JS validation as below:
function isNumberKey(evt){ var charCode = (evt.which) ? evt.which : evt.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } <input name="someid" type="number" onkeypress="return isNumberKey(event)"/>
If you want to allow decimals replace the "if condition" with this:
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
Source: HTML text input allow only numeric input
JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/
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