How to limit the number of numbers allowed to enter html (live) numbers?

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

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

But the browser will check the correctness of the input only when I click the "send" button. I want to say: let's say that the user enters “1234” into the field, and then tries to dial “1” or any other number. I want him to not be able to do this. Basically, when he continues to press any of the buttons / letters, I want them to just not appear in the field.

How can i achieve this?

+4
source share
5 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">
Hide result

,

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
Hide result
+5
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">
+2
    <input type="number" id="userNumber">
        <input type="submit" id="numberSubmit" onclick="CheckValid()">
        <label id="warningMessage"></label>
        <script>
            function CheckValid(){
            var number = document.getElementById("userNumber").value;
            if(isNaN(number) || number.length != 4)
            {
                document.getElementById("warningMessage").innerHTML = "Invalid";
            }   
            else{
                document.getElementById("warningMessage").innerHTML = "Valid";
            }
            }
        </script>
+1
source

Sweet and simple.

<input id="a" type="text" maxLength = "4" 
onkeypress='return event.charCode > 48 && event.charCode < 57'>

Note. The solution is based on the community wiki: HTML text input only allows numeric input

+1
source
<input type="number" max="9999" maxlength="4">
-1
source

Source: https://habr.com/ru/post/1599635/


All Articles