【问题标题】:HTML Input type number is not working with maxlengthHTML 输入类型编号不适用于 maxlength
【发布时间】:2021-01-02 19:58:05
【问题描述】:

我正在使用下面的 html 标记并且无法获得对数字的限制,我只需要用户输入 12 位数字,但是默认情况下按照 HTML 标记“maxlength”不适用于<input type ="number">,我尝试了 min 和最大标签,它也没有帮助。

您能否分享一下仅在 HTML 中执行此操作的方法?

<input type="number" name="Aadhar" maxlength="12" placeholder="xxxx-xxxx-xxxx" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}" required>

【问题讨论】:

  • 我注意到您使用的是数字输入,但占位符和模式不是数字 (xxxx-xxxx-xxxx)。如果您使用文本输入,这可能会更好吗?
  • 我尝试输入文本,它限制了长度,但是它需要字母数字。

标签: html maxlength input-type-range


【解决方案1】:

最大长度不适用于 click here to read more 来解决您的问题

【讨论】:

    【解决方案2】:

    很遗憾,number 类型的输入不支持 maxlength 属性。因此,最好的办法是使用JS。请参阅以下文档,它们可能会提供一些清晰的信息。

    【讨论】:

      【解决方案3】:

      使用 ma​​x 代替 maxlength

      <input type="number" name="Aadhar" max="12" placeholder="xxxx-xxxx-xxxx" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}" required>
      

      当用户点击提交按钮时,它会显示该值应小于 12。 这只能在表单内使用。

      【讨论】:

      • 我认为这会将最大值与最大长度混淆。
      【解决方案4】:

      你可以试试这个。

      function numOnly(id) {
          // Get the element by id
          var element = document.getElementById(id);
          // Use numbers only pattern, from 0 to 9 with \-
          var regex = /[^0-9\-]/gi;
          // Replace other characters that are not in regex pattern
          element.value = element.value.replace(regex, "");
      }
      &lt;input type="text" id="number" oninput="numOnly(this.id);" name="Aadhar" maxlength="14" placeholder="xxxx-xxxx-xxxx" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}" required/&gt;

      【讨论】:

      • 谢谢你的回复,我只需要在 HTML 中做,没有 JS。
      猜你喜欢
      • 2016-08-16
      • 2019-09-09
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 2018-02-18
      • 2012-03-22
      相关资源
      最近更新 更多