Limit input html

Posted on

Question :

I want to put an input in html and I want to limit only 2 numbers.

<input type="text" name="Dia" maxlength="2" size="2" >

I tried this one but letters still appear.


Answer :

To limit input to numbers just change type from text to number :

<form action="#">
  <input type="number" name="Dia" min="1" max="31">
  <input type="submit">

Even if you want to limit from 1 to 31 (assuming it is the number of days in the month) you can do this with mim and max .

Note: This type number does not work in IE9 or earlier versions.

In case you need it to work in IE9 or earlier you can use JavaScript:

<form action="#">
  <input type="text" maxlength="2" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
  <input type="submit">

Sample font with onkeypress .


You can use the event onkeypress :

<input type="text" maxlength="2" onkeypress="if (!isNaN(String.fromCharCode(window.event.keyCode))) return true; else return false;">

Every time a key is pressed within%%, the event will be activated, and it will check whether the key presses a number or not, if it is a letter it returns% with%, if it is a number it will return% with% and it will appear no input .

See how you got on Fiddle.


Leave a Reply

Your email address will not be published. Required fields are marked *