4

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?

3
  • 1
    Unfortunately maxlength only works with type="text". Try it here. Commented Jul 25, 2015 at 9:21
  • @initialxy Interesting. I didn't know that. In that case I would probably use text and don't bother with number since it can't restrict the input. Commented Jul 25, 2015 at 9:39
  • 1
    @SebastianNette see here for a complete list of supported attributes depending on input type: w3.org/TR/html5/forms.html#concept-input-apply Commented Jul 25, 2015 at 9:42

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

6 Comments

For restricting the field to number only by not using type=number, please visit Restrict to Number
It would be better to listen to the input event instead and then just cut everything off that exceeds the retriction. E.g.Copy&Paste or using those arrows at the input are not affected.
@SebastianNette valid point but see question 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
So If OP wants such restriction, OP can add extra code to do that using events like change etc, also event input is not broadly supported event
here e stands for exponential number so 2e10 is allowed as its a number
|
2
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">

1 Comment

Thanks, but I prefer not to use jQuery since I'm still quite a beginner in JS.
1
    <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 Comment

Thanks, but that only checks if the input is valid when I click on the box.
1

Sweet and simple.

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

Note: Solution based on a community wiki : HTML Text Input allow only Numeric input

1 Comment

AFAIK this removes mobile support; several mobile browsers will pop up a number pad instead of a keyboard when they encounter type="number" and this prevents that.
-1
<input type="number" max="9999" maxlength="4">

1 Comment

Unfortunately maxlength only works with type="text". Try it here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.