Allow only 2 numbers for input type number

How to set the range between 0 and 99 to the input type number? I use HTML5 ( min="0" max="99") attributes , but it does not work, and as far as I know, this kind of attribute is not supported by some browsers.

Therefore, I use this script that blocks non-numeric characters, but I want to limit the number to 99 (only 2 digits). How can i do this?

I also want to allow users to use the keyboard to enter numbers.

$(".js-number").numeric();

jsFiddle

+4
source share
3 answers

, $( ". js-number" ). numeric();
.
maxlength , , JavaScript .

 <input type="number" class="js-number" min="0" max="99" value="0">   
 <script>
    $(".js-number").bind('keydown', function(e){
       var targetValue = $(this).val();
       if (e.which ===8 || e.which === 13 || e.which === 37 || e.which === 39 || e.which === 46) { return; }

       if (e.which > 47 &&  e.which < 58  && targetValue.length < 2) {
          var c = String.fromCharCode(e.which);
          var val = parseInt(c);
          var textVal = parseInt(targetValue || "0");
          var result = textVal + val;

          if (result < 0 || result > 99) {
             e.preventDefault();
          }

          if (targetValue === "0") {
            $(this).val(val);
            e.preventDefault();
          }
       }
       else {
           e.preventDefault();
       }
    });
 </script>
+2
<input class="test-input" type="number" maxlength="12" />
<script>
$('.test-input').unbind('keyup change input paste').bind('keyup change input paste',function(e){
    var $this = $(this);
    var val = $this.val();
    var valLength = val.length;
    var maxCount = $this.attr('maxlength');
    if(valLength>maxCount){
        $this.val($this.val().substring(0,maxCount));
    }
}); 
</script>
+1

You can set the following:

<input type="text" class="js-number" maxlength="2">
0
source

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


All Articles