Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 990
chtenb Avatar asked Dec 19 '12 12:12

chtenb


People also ask

How do I make input 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 I restrict input to numbers in HTML?

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

How do I restrict only 10 numbers in a text box in HTML?

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.


1 Answers

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/

like image 154
Viral Patel Avatar answered Sep 25 '22 21:09

Viral Patel