Limit input html

3

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.

    
asked by anonymous 27.01.2015 / 11:20

2 answers

6

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

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

Sample font with onkeypress .

    
27.01.2015 / 11:38
2

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.

    
27.01.2015 / 11:39