Coder Perfect

How can I construct an HTML input tag that only accepts numbers?


I need to ensure that a specific input> field accepts only numbers as a value. The input does not belong in a form. As a result, it is not submitted, and verifying while submitting is not an option. I don’t want the user to be able to type anything except numbers.

Is there a simple way to accomplish this?

Asked by chtenb

Solution #1

To limit only number entries, use HTML5 input type number:

<input type="number" name="someid" />

Only HTML5-compliant browsers will be able to use this. Make sure the doctype of your HTML document is:

For transparent support in older browsers, see

There is now a new and extremely simple solution for this:

See this answer for more information, or test it yourself on JSFiddle.

You can use the following JS validation for generic purposes:

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)"/>

Replace the “if condition” with this if you wish to accept decimals:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

Only numeric input is allowed in HTML text input.

JSFiddle demo:

Answered by Viral Patel

Solution #2

In HTML5, you can also utilize the pattern attribute:

<input type="text" name="name" pattern="[0-9]" title="Title" /> 

Input validation tutorial

If your doctype isn’t html, though, I believe you’ll need to utilize javascript/jquery.

Answered by martincarlin87

Solution #3

Code that is simple and quick

<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />

This will only allow you to use numbers and backspace.

Use this code fragment if you need the decimal component as well.

<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))" />

Answered by abhijithvijayan

Solution #4

Please use this code in conjunction with the input box.

<input type="text" name="price" id="price_per_ticket" class="calculator-input" onkeypress="return event.charCode >= 48 && event.charCode <= 57"></div>

It’ll turn out well.

Answered by subindas pm

Solution #5

An input type=”number” /> can be used. Only numbers will be accepted in the other input box as a result of this.


Please note that only newer browsers allow the input type=”number” tag.

You can use javascript to validate the input in Firefox:

Update 2018-03-12: Browser support has greatly improved, and currently includes the following:

Answered by starbeamrainbowlabs

Post is based on