元素,maxlength不起作用。如何限制该maxlength数字元素?..."> 元素,maxlength不起作用。如何限制该maxlength数字元素?..."/> 元素,maxlength不起作用。如何限制该maxlength数字元素?..."> 元素,maxlength不起作用。如何限制该maxlength数字元素?...">

如何限制HTML5“数字”元素中的可能输入?

html HTML

村村番长

2020-03-23

对于<input type="number">元素,maxlength不起作用。如何限制该maxlength数字元素?

第2990篇《如何限制HTML5“数字”元素中的可能输入?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

17个回答
Tom凯 2020.03.23

我知道已经有一个答案了,但是如果您想让输入的行为与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();
Mandy 2020.03.23

对于具有长度限制的数字输入,您也可以尝试此操作

<input type="tel" maxlength="3" />
神乐 2020.03.23

要使用的更相关的属性是minmax

小卤蛋小胖逆天 2020.03.23

与一样type="number",您可以指定max而不是maxlength属性,这是可能的最大数目。因此,用4位数字max应该是9999,5位数字99999,依此类推。

另外,如果要确保它是正数,可以设置min="0",以确保为正数。

西里Near 2020.03.23
<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />

或者如果您希望不输入任何内容

<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />
猴子 2020.03.23

为数字输入设置最大长度的一种简单方法是:

<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
路易斯丁LEY 2020.03.23

Maycow Moura的答案是一个好的开始。但是,他的解决方案意味着,当您输入第二位数字时,将停止对该字段的所有编辑。因此,您不能更改值或删除任何字符。

以下代码在2处停止,但允许继续编辑;

//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"
西里古一 2020.03.23

最大长度不能以<input type="number"我所知的最好方式使用oninput事件来限制最大长度请参阅以下代码以实现简单的实现。

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

正如其他人所述,min / max与maxlength不同,因为人们仍然可以输入一个大于您期望的最大字符串长度的浮点数。要真正模拟maxlength属性,您可以在紧急情况下执行以下操作(这等效于maxlength =“ 16”):

<input type="number" oninput="if(value.length>16)value=value.slice(0,16)">
Tony凯 2020.03.23

可以说,您希望最大允许值为1000-键入或使用微调框。

您可以使用以下方式限制微调器的值: type="number" min="0" max="1000"

并限制什么是键盘使用JavaScript类型的: onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }

<input type="number" min="0" max="1000" onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }">
Stafan路易 2020.03.23

//For Angular I have attached following snippet.
<div ng-app="">
  <form>
    Enter number: <input type="number" ng-model="number" onKeyPress="if(this.value.length==7) return false;" min="0">
  </form>
  <h1>You entered: {{number}}</h1>
</div>

如果使用“ onkeypress”事件,则在开发(单元测试)时不会受到任何用户限制。如果您有不允许特定限制后不允许用户输入的要求,请看一下此代码,然后尝试一次。

十三 2020.03.23

您可以将其指定为文本,但可以添加仅与数字匹配的数字:

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

它可以完美运行,并且可以在移动设备上(在iOS 8和Android上测试)弹出数字键盘。

乐Jim 2020.03.23

这非常简单,您可以使用一些JavaScript来模拟一个maxlength,并检查出来:

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

您可以像这样组合所有这些:

<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: 请注意,允许输入的小数点以上可能会弄乱数字值。

乐米亚 2020.03.23

如果要在Mobile Web解决方案中希望用户看到数字键盘而不是全文键盘。使用type =“ tel”。它将与maxlength一起使用,可避免创建额外的javascript。

最大值和最小值仍将允许用户键入超出最大值和最小值的数字,这不是最佳选择。

斯丁 2020.03.23

您可以指定minmax属性,这将仅允许在特定范围内输入。

<!-- equivalent to maxlength=4 -->
<input type="number" min="-9999" max="9999">

但是,这仅适用于微调器控制按钮。尽管用户可以键入比允许的数字大的数字max,但表单不会提交。

Chrome的验证消息中的数字大于最大值
屏幕快照取自Chrome 15

可以oninput在JavaScript中使用HTML5 事件来限制字符数:

myInput.oninput = function () {
    if (this.value.length > 4) {
        this.value = this.value.slice(0,4); 
    }
}
米亚 2020.03.23

并且您可以添加一个max属性,属性将指定您可以插入的最大数字

<input type="number" max="999" />

如果同时添加maxmin,则可以指定允许值的范围:

<input type="number" min="1" max="999" />

The above will still not stop a user from manually entering a value outside of the specified range. Instead he will be displayed a popup telling him to enter a value within this range upon submitting the form as shown in this screenshot:

在此处输入图片说明

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android