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


当前回答

或者如果你的最大值是99,最小值是0,你可以把它加到输入元素中(你的值会被你的最大值重写)。

<input type="number" min="0" max="99" 
   onKeyUp="if(this.value>99){this.value='99';}else if(this.value<0){this.value='0';}"
id="yourid">

然后(如果你想),你可以检查输入的是否真的数字

其他回答

    <input type="number" maxlength="6" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">

这对我来说没有任何问题

如果有人在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来改变你可以输入的数字数量)。我希望这能帮助到那些正在为这个问题而挣扎的人。如果你想了解切片方法的功能,可以点击这里

这可能会帮助到某些人。

用一点javascript,你可以搜索所有的datetime-local输入,搜索用户试图输入的年份,大于100年后:

$('input[type=datetime-local]').each(function( index ) {

    $(this).change(function() {
      var today = new Date();
      var date = new Date(this.value);
      var yearFuture = new Date();
      yearFuture.setFullYear(yearFuture.getFullYear()+100);

      if(date.getFullYear() > yearFuture.getFullYear()) {

        this.value = today.getFullYear() + this.value.slice(4);
      }
    })
  });

我知道已经有一个答案,但如果你想让你的输入行为完全像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();

梅考·莫拉的回答是一个好的开始。 然而,他的解决方案意味着当您输入第二个数字时,所有字段的编辑都会停止。因此,您不能更改值或删除任何字符。

下面的代码停在2,但允许继续编辑;

//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"