How to make HTML input tag only accept numerical values?
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?
HTML 5
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.
JavaScript
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/
You can also use the pattern attribute in html5:
<input type="text" name="name" pattern="[0-9]" title="Title" />
Input validation tutorial
Although, if your doctype isn't html
then I think you'll need to use some javascript/jquery.
Quick and Easy Code
<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />
This will permit usage of numbers and backspace only.
If you need decimal part too, use this code fragment
<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))" />
Please try this code along with the input field itself
<input type="text" name="price" id="price_per_ticket" class="calculator-input" onkeypress="return event.charCode >= 48 && event.charCode <= 57"></div>
it will work fine.
You can use an <input type="number" />
. This will only allow numbers to be entered into othe input box.
Example: http://jsfiddle.net/SPqY3/
Please note that the input type="number"
tag is only supported in newer browsers.
For firefox, you can validate the input by using javascript:
http://jsfiddle.net/VmtF5/
Update 2018-03-12: Browser support is much better now it's supported by the following:
- Chrome 6+
- Firefox 29+
- Opera 10.1+
- Safari 5+
- Edge
- (Internet Explorer 10+)