对于<input type="number">元素,maxlength无效。如何限制该数字元素的最大长度?


当前回答

下面是使用maxlength的最简单的解决方案:

<form>
   <input class="form-control" id="code_pin" oninput="if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" maxlength="4">
</form>

其他回答

我知道已经有一个答案,但如果你想让你的输入行为完全像maxlength属性或尽可能接近,使用以下代码:

(function($) {
 methods = {
    /*
     * addMax will take the applied element and add a javascript behavior
     * that will set the max length
     */
    addMax: function() {
        // set variables
        var
            maxlAttr = $(this).attr("maxlength"),
            maxAttR = $(this).attr("max"),
            x = 0,
            max = "";

        // If the element has maxlength apply the code.
        if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {

            // create a max equivelant
            if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
                while (x < maxlAttr) {
                    max += "9";
                    x++;
                }
              maxAttR = max;
            }

            // Permissible Keys that can be used while the input has reached maxlength
            var keys = [
                8, // backspace
                9, // tab
                13, // enter
                46, // delete
                37, 39, 38, 40 // arrow keys<^>v
            ]

            // Apply changes to element
            $(this)
                .attr("max", maxAttR) //add existing max or new max
                .keydown(function(event) {
                    // restrict key press on length reached unless key being used is in keys array or there is highlighted text
                    if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
                });;
        }
    },
    /*
     * isTextSelected returns true if there is a selection on the page. 
     * This is so that if the user selects text and then presses a number
     * it will behave as normal by replacing the selection with the value
     * of the key pressed.
     */
    isTextSelected: function() {
       // set text variable
        text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return (text.length > 0);
    }
};

$.maxlengthNumber = function(){
     // Get all number inputs that have maxlength
     methods.addMax.call($("input[type=number]"));
 }

})($)

// Apply it:
$.maxlengthNumber();

啊。就像有人在实施过程中半途而废,以为没人会注意到。

不管出于什么原因,上面的答案没有使用min和max属性。这个jQuery完成它:

    $('input[type="number"]').on('input change keyup paste', function () {
      if (this.min) this.value = Math.max(parseInt(this.min), parseInt(this.value) || 0);
      if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
    });

如果你是那种“jQuery-is-the-devil”类型,它也可能作为一个命名函数“oninput”使用jQuery。

如果有人在React中挣扎,我发现最简单的解决方案是使用onChange函数,像这样:

    const [amount, setAmount] = useState("");
    
   return(
    <input onChange={(e) => {
    setAmount(e.target.value);
    if (e.target.value.length > 4) {
         setAmount(e.target.value.slice(0, 4));
    }
    }} value={amount}/>)

所以这基本上做的是,它获取输入的值,如果输入值长度大于4,它就会切片它之后的所有数字,所以你只得到前4个数字(当然,你可以通过改变代码中的所有4来改变你可以输入的数字数量)。我希望这能帮助到那些正在为这个问题而挣扎的人。如果你想了解切片方法的功能,可以点击这里

另一种选择是为任何具有maxlength属性的东西添加一个侦听器,并将切片值添加到其中。假设用户不想在与输入相关的每个事件中使用函数。下面是一个代码片段。忽略CSS和HTML代码,JavaScript才是最重要的。

// Reusable Function to Enforce MaxLength function enforce_maxlength(event) { var t = event.target; if (t.hasAttribute('maxlength')) { t.value = t.value.slice(0, t.getAttribute('maxlength')); } } // Global Listener for anything with an maxlength attribute. // I put the listener on the body, put it on whatever. document.body.addEventListener('input', enforce_maxlength); label { margin: 10px; font-size: 16px; display: block } input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px } span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 } <label for="test_input">Text Input</label> <input id="test_input" type="text" maxlength="5"/> <span>set to 5 maxlength</span> <br> <label for="test_input">Number Input</label> <input id="test_input" type="number" min="0" max="99" maxlength="2"/> <span>set to 2 maxlength, min 0 and max 99</span>

简单的解决方法,

输入滚动事件 通过键盘复制粘贴 通过鼠标复制粘贴 输入类型等情况 <输入id = " maxLengthCheck " name = " maxLengthCheck " type = "数量" 一步= " 1 " min = " 0 " oninput = "。Value = this。取值为> 5 ?5: Math.abs(this.value)"/>

这是有条件的。值> 5,只需更新5与您的最大限制。

解释:

如果我们的输入数大于我们的极限更新输入值this。Math.abs(this.value) 否则就达到最大限度,也就是5。