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


当前回答

这很简单,用一些javascript你可以模拟一个maxlength,看看:

//maxlength="2"
<input type="number" onKeyDown="if(this.value.length==2) return false;" />

其他回答

我知道已经有一个答案,但如果你想让你的输入行为完全像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"事件,那么你在开发(单元测试)时将不会受到任何用户限制。如果你有要求,不允许用户进入特定的限制后,看看这段代码,并尝试一次。

你可以像这样把所有这些组合起来:

<input name="myinput_drs"
oninput="maxLengthCheck(this)"
type = "number"
maxlength = "3"
min = "1"
max = "999" />

<script>
  // This is an old version, for a more recent version look at
  // https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
  function maxLengthCheck(object)
  {
    if (object.value.length > object.maxLength)
      object.value = object.value.slice(0, object.maxLength)
  }
</script>

更新: 您可能还希望防止输入任何非数字字符,因为object。Length对于数字输入来说是一个空字符串,因此它的长度为0。因此maxLengthCheck函数将不起作用。

解决方案: 看这个或这个例子。

演示-查看完整版本的代码在这里: http://jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/

更新2:下面是更新代码: https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/

更新3: 请注意,允许输入超过一个小数点可能会导致数值混乱。

对于有长度限制的数字输入,您也可以尝试这种方法

<input type="tel" maxlength="3" />

你可以将它指定为文本,但要添加只匹配数字的pettern:

<input type="text" pattern="\d*" maxlength="2">

它非常完美,而且在移动设备上(在iOS 8和Android上进行了测试),数字键盘也会弹出。