Limit html input

Asked

Viewed 55,591 times

5

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

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

I tried this but still letters appear.

2 answers

11


To limit the input the numbers just change the type of text for number:

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

Still if you want to limit from 1 to 31 (imagining that it is the number of days of the month) you can do it with mim and max.

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

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>

Source of the example with onkeypress.

  • Changing the type for number does not solve, as it still accepts Letters. Alias it will make the input in a number "selector", but it will not prevent the user from typing numbers.

  • Does not accept letters, look forehead @Meuchapeu. Gives submit see if you accept.

  • Correct, by clicking on submit it will warn that it accepts only numbers, but will not prevent the user from typing the letters. Unlike the event onkeypress which only allows typing numbers.

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 selected within the input the event will be activated, and check whether or not the Presiona key is a number, if it is return letters false, if number returns true and will appear on input.

See how it looks on Fiddle.

Note: The event onkeypress is not working on Firefox

  • The onkeypress works yes in Firefox, what happens is that the window.event does not exist. A solution with the same result, working also in Firefox is this: return !isNaN(event.key);. But this approach has a problem as it prevents the user from interacting in the input using arrows, Backspace, delete, etc...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.