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

牧云@^-^@ 提交于 2019-12-01 05:56:31
mplungjan

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;
  });      
});
Roohbakhsh Masoud

I don't know my answer is useful for you? But i happy if i can help you. you should write a js method and then use it in your html page.

function limit(element) {
  var max_chars = 2;

  if(element.value.length > max_chars) {
    element.value = element.value.substr(0, max_chars);
  }
}


<input type="number" onkey ="limit(this);" onkeyup="limit(this);">
marooou

Since there is no uniform support for HTML5 input types I suggest using this script template until all browsers will support them.

$(".quantity").each(function() {
    $(this).attr("type", "text")
    var min = $(this).attr("min");
    var max = $(this).attr("max");
    $(this).removeAttr("min").removeAttr("max");
    $(this).keyup(function(){
        var $field = $(this);
        if ($field.val().length > Number($field.attr("maxlength"))) {
            var value = $field.val().slice(0, 5);
            //   add js integer validation here using min and max
            $field.val(value);
        }
    });
});

Then we can simply leave HTML5 elements untouched

to dynamically set max limit

function limit(element,max_chars) {

  if(element.value.length > max_chars) {
    element.value = element.value.substr(0, max_chars);
  }
}


<input type="number" onkey ="limit(this);" onkeyup="limit(this,2);">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!