Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict the amount of numbers allowed in the html number input (live)?

Basically, I have a number input field on my page, and I want users to only be able to insert 4 digits in the field. I know I can do something like this:

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

But the browser is going to check if the input is correct only when I press the "submit" button. What I want to do is : Let's say that the user types "1234" in the box, and after that he tries to type "1" or any other number. I want him to not be able to do that. Basically when he keeps pressing any of the buttons/letters, I want them to simply not appear in the box.

How can I achieve this?

like image 380
bool3max Avatar asked Feb 09 '23 11:02

bool3max


2 Answers

var numberInput = document.getElementById('a');

numberInput.onkeypress = function(){
  console.log(this.value.length)
  if(this.value.length>3)
    return false
}
<input id="a" type="number">

For making it generalised, use below code

var inputs = document.querySelectorAll('.restrictLength');

for( i  in inputs){
   inputs[i].onkeypress = function(){
         console.log(this.id,this.value.length,this.getAttribute('data-restrict-to'));
         if(this.value.length>Number(this.getAttribute('data-restrict-to'))-1)
           return false
}

}
<input id="a" class="restrictLength" type="number" data-restrict-to="4"> restrict to 4
<br/>
<br/>
<input id="b" class="restrictLength" type="number" data-restrict-to="2"> restrict to 2
like image 183
vinayakj Avatar answered Feb 11 '23 23:02

vinayakj


var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        $(function () {
            $("#a").bind("keypress", function (e) {
                if(this.value.length>3){ return false}
                var keyCode = e.which ? e.which : e.keyCode
                var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);

                return ret;
            });
            $("#a").bind("paste", function (e) {
                return false;
            });
            $("#a").bind("drop", function (e) {
                return false;
            });
        });

    <input id="a" type="number">
like image 39
Animesh Kumar Avatar answered Feb 12 '23 01:02

Animesh Kumar