Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only numbers to be typed in a textbox [duplicate]

Tags:

javascript

How to allow only numbers to be written in this textbox ?

<input type="text" class="textfield" value="" id="extra7" name="extra7"> 
like image 962
EnexoOnoma Avatar asked Sep 03 '11 20:09

EnexoOnoma


People also ask

How do I allow only the numeric value in a text box?

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 only input numbers?

To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.


2 Answers

You could subscribe for the onkeypress event:

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" /> 

and then define the isNumber function:

function isNumber(evt) {     evt = (evt) ? evt : window.event;     var charCode = (evt.which) ? evt.which : evt.keyCode;     if (charCode > 31 && (charCode < 48 || charCode > 57)) {         return false;     }     return true; } 

You can see it in action here.

like image 107
Darin Dimitrov Avatar answered Sep 21 '22 05:09

Darin Dimitrov


With HTML5 you can do

<input type="number"> 

You can also use a regex pattern to limit the input text.

<input type="text" pattern="^[0-9]*$" /> 
like image 20
powtac Avatar answered Sep 18 '22 05:09

powtac