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

前端 未结 4 369
自闭症患者
自闭症患者 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:42


    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

提交回复
热议问题