How to restrict user input character length of HTML5 input type=“number”?

前端 未结 4 426
自闭症患者
自闭症患者 2021-01-13 11:44

How do I restrict user input to a given length in an HTML5 input[type=number] textbox?

the answers to

How can I limit possible inputs in a HTML

4条回答
  •  长情又很酷
    2021-01-13 12:34

    Here is my suggestion after testing a few things

    1. it handles more than one field with the quantity class
    2. it handles illegal input where supported
    3. initialises by storing all defaultValues of the fields with the class
    4. handles a weirdness with .index()
    5. works in IE<10 too
    6. tested in Safari 5.1 on Windows - it reacted to the is(":invalid") which however is invalid in IE8

    Live Demo

    var inputQuantity = [];
    $(function() {
      $(".quantity").each(function(i) {
        inputQuantity[i]=this.defaultValue;
         $(this).data("idx",i); // save this field's index to access later
      });
      $(".quantity").on("keyup", function (e) {
        var $field = $(this),
            val=this.value,
            $thisIndex=parseInt($field.data("idx"),10); // retrieve the index
        // NOTE :invalid pseudo selector is not valid in IE8 so MUST be last
        if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid") ) { 
            this.value = inputQuantity[$thisIndex];
            return;
        } 
        if (val.length > Number($field.attr("maxlength"))) {
          val=val.slice(0, 5);
          $field.val(val);
        }
        inputQuantity[$thisIndex]=val;
      });      
    });
    

提交回复
热议问题