【问题标题】:How to set Max-Length in Input tag type is Number? [duplicate]如何在输入标签类型中设置最大长度为数字?
【发布时间】:2021-11-01 19:23:27
【问题描述】:

如何在 HTML 5 中设置 Input 标签类型中的 Max-Length 为 Number?

<html>
<body>
<input type="number" maxlength="10">
</body>
</html>

【问题讨论】:

标签: html input maxlength html5-input-number


【解决方案1】:

根据 MDN:

对于maxLength

对文本、搜索、url、电话、电子邮件和密码有效,它定义了用户可以在字段中输入的最大字符数(作为 UTF-16 代码单元)。这必须是 > 一个大于等于 0 的整数值。如果未指定 maxlength,或者 >specified 无效值,则该字段没有最大长度。该值还必须大于或>等于 minlength 的值。

所以type=number 被忽略了。这是使用该模式的解决方法

&lt;input type="text" pattern="\d*" maxlength="4"&gt;

【讨论】:

    【解决方案2】:

    <!DOCTYPE html>
    <html>
    
    <body>
    
      <h2>JavaScript Validation</h2>
    
      <p>Enter a number and click OK:</p>
    
      <input id="id1" type="number" min="100" max="300" required>
      <button onclick="myFunction()">OK</button>
    
      <p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>
    
      <p id="demo"></p>
    
      <script>
        function myFunction() {
          const inpObj = document.getElementById("id1");
          if (!inpObj.checkValidity()) {
            document.getElementById("demo").innerHTML = inpObj.validationMessage;
          } else {
            document.getElementById("demo").innerHTML = "Input OK";
          }
        }
      </script>
    
    </body>
    
    </html>

    【讨论】:

    • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2017-10-19
    • 2020-01-05
    • 1970-01-01
    • 2021-12-11
    • 2022-01-17
    • 2018-01-03
    相关资源
    最近更新 更多