0

I want to limit the input type number to maximum 5 numbers, I am using below code, which is working well, only issue is that for backspace I have to use event.keycode which I dont want to use. Is there any alternative apart from usking keycode of backspace.

var input = document.getElementById('input');
input.addEventListener('keypress',showData,false)
function showData(event)
{
   if(event.target.value.length<=5)
   {
      return true;
   }
   else
   {
      event.preventDefault();
   }

}
Rajesh Jangid
  • 724
  • 6
  • 13
user3045179
  • 321
  • 4
  • 20

4 Answers4

3

If you want it so if the user tries to type more than 5 numbers it only keeps the 5 numbers:

input.oninput = function() {
    if (this.value.length > 5) {
        this.value = this.value.slice(0,5); 
    }
}
0

Why don't you just use:

<input type="number" max="99999">

This will still not stop a user from manually entering a value larger than 99999, but the input element will be invalid.

henrikmerlander
  • 1,554
  • 13
  • 20
0
<input type="number" max="99999" />

How can I limit possible inputs in a HTML5 "number" element?

Community
  • 1
  • 1
a45b
  • 489
  • 3
  • 19
0

<form>
<input required type="text" name="inputname" pattern="[0-9]{5,}">
  <input type="submit" value="submit">
</form>
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109