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


当前回答

如果您正在寻找一种移动Web解决方案,希望用户看到数字键盘而不是全文键盘。使用类型=“电话”。它将与maxlength一起工作,这将节省您创建额外的javascript。

Max和Min仍然允许用户输入超过Max和Min的数字,这不是最佳的。

其他回答

这可能会帮助到某些人。

用一点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();

//对于Angular,我添加了如下代码片段。 < div ng-app = " " > < >形式 输入数字:<input type="number" ng-model="number" onKeyPress="if(this.value.length==7) return false;" min="0"> > < /形式 <h1>输入:{{number}}</h1> < / div >

如果你使用"onkeypress"事件,那么你在开发(单元测试)时将不会受到任何用户限制。如果你有要求,不允许用户进入特定的限制后,看看这段代码,并尝试一次。

我发现你不能使用任何onkeydown, onkeypress或onkeyup事件的完整解决方案,包括移动浏览器。顺便说一下,onkeypress已弃用,不再出现在chrome/opera的android(见:UI事件 W3C工作草案,2016年8月4日)。

我只使用oninput事件找到了一个解决方案。 你可能需要做额外的数字检查,如负号/正号或小数和千个分隔符等,但作为一个开始,以下应该足够了:

函数checkMaxLength(事件){ //准备恢复之前的值 如果这一点。oldValue === undefined) { 这一点。oldValue = this.defaultValue; } 如果(this.value。长度> this.maxLength) { //设置回前一个值 这一点。value = oldVal; } 其他{ //存储之前的值。 这一点。oldValue = this.value; //对+/-或。/等进行额外检查 //同时考虑合并'maxlength' //使用'min'和'max'来防止错误提交。 } }

我还建议将maxlength与min和max结合起来,以防止如上所述的错误提交。

或者如果你的最大值是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">

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