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?

bool3max
  • 2,748
  • 5
  • 28
  • 57
  • 1
    Unfortunately `maxlength` only works with `type="text"`. Try it [here](http://jsfiddle.net/yq91ejox/1/). – initialxy Jul 25 '15 at 09: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. – Sebastian Nette Jul 25 '15 at 09:39
  • 1
    @SebastianNette see here for a complete list of supported attributes depending on input type: http://www.w3.org/TR/html5/forms.html#concept-input-apply – Zimmi Jul 25 '15 at 09:42

5 Answers5

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
vinayakj
  • 5,591
  • 3
  • 28
  • 48
  • For restricting the field to number only by not using `type=number`, please visit [Restrict to Number](http://stackoverflow.com/questions/30287531/input-number-validation-restrict-to-enter-only-numbers-or-digits-int-float/30287532#30287532) – vinayakj Jul 25 '15 at 09:33
  • 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. – Sebastian Nette Jul 25 '15 at 09:46
  • @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` – vinayakj Jul 25 '15 at 09:48
  • 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 – vinayakj Jul 25 '15 at 09:51
  • Thanks, that's the simplest answer that solves my problem. But something's not right. I can't write any letters in the box, expect the letter "e". I don't know why that happens. Anyways, thanks! – bool3max Jul 25 '15 at 13:47
  • 1
    here `e` stands for `exponential` number so `2e10` is allowed as its a number – vinayakj Jul 25 '15 at 13:48
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
    <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>
Yan
  • 431
  • 1
  • 4
  • 6
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

Community
  • 1
  • 1
Sarath Chandra
  • 1,850
  • 19
  • 40
  • 2
    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. – Nic Jul 25 '15 at 10:45
-1
<input type="number" max="9999" maxlength="4">
Shrinivas Pai
  • 7,491
  • 4
  • 29
  • 56
  • 3
    Unfortunately `maxlength` only works with `type="text"`. Try it [here](http://jsfiddle.net/yq91ejox/1/). – initialxy Jul 25 '15 at 09:21