【问题标题】:Input with type="number" that allows only numbers to be typed输入 type="number" 只允许输入数字
【发布时间】:2021-07-15 13:11:08
【问题描述】:

我想创建一个只能写入自然数的输入字段。 (是的,我知道这可能是一种不好的做法,因为用户没有得到任何反馈)。 如果您键入的不是数字,它不应该出现在输入中。 我想使用纯 JavaScript(没有 JQuery)。

这就是我通常的做法:

<input oninput="this.value = this.value.replace(/\D+/g, '')">

但我发现,&lt;input type="number"&gt; 更适合移动设备,因为它不显示整个键盘,而只显示数字。

所以我的问题是,我如何将type="number" 与过滤相结合(并使其与剪切/复制/粘贴兼容)?

如果输入任何非数字字符,&lt;input type="number"&gt;-元素的值始终为空字符串。所以我上面的过滤方法不起作用。有什么解决办法吗?

如果没有,我将不得不监听 keydown、paste、cut 以及可能更多的事件。我必须考虑哪些事件,我将如何实现它,还有没有我忽略的更简单的方法?

【问题讨论】:

  • &lt;input type="number" /&gt; 缺少什么?不清楚你不能用 type="number" 做什么 - 用户不能在其中输入除数字以外的任何内容
  • @mplungjan 我想它对用户的影响还不够。
  • @mplungjan 您可以在 type="number" 的输入中键入任何字符。这只是无效的。但我想完全阻止用户在输入框中输入其他字符。
  • 你用的是什么浏览器,输入类型号不允许我输入任何我想要的东西。

标签: javascript html validation input


【解决方案1】:

尝试使用inputmode 属性

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode

&lt;input inputmode="numeric" oninput="this.value = this.value.replace(/\D+/g, '')"  /&gt;

参考文献

https://css-tricks.com/finger-friendly-numerical-inputs-with-inputmode

【讨论】:

    【解决方案2】:

    在 Chrome 中测试(只能输入数字,-和e

    在 Firefox 中,您可以输入但不能提交

    Try typing anything and then hit enter
    <form>
    <input type="number" required />
    </form>

    那么让我们试试这个 - 如果在输入字符时可以清除该字段,我们不需要 keyUp 等

    如果您在任何地方输入字符,Firefox 将返回空字符串,Chrome 将不允许该字符

    document.querySelector("form").addEventListener("input",function(e) {
      const tgt = e.target;
      if (tgt.type && tgt.type==="number") { 
        const val = tgt.value;
        const nums = val.replace(/[^\d.-]/g, '');
        if (!/\d+/.test(val)) tgt.value="";
      }  
    })
    Try typing anything and then hit enter
    <form>
    <input type="number" required />
    </form>

    【讨论】:

    • 我在使用 Firefox 浏览器(最新版本)的台式计算机(Windows)上。在这里你可以。如果你愿意,我可以测试其他浏览器,但我强烈认为它会给出相同的结果。
    • 啊,我只用Chrome(ium)
    • @FireFuro99 您可以编写它们,但它们无效。如果您有1a2,则无法提交表单。
    • 是的,我知道这将无效。但我想首先阻止用户在输入框中输入非数字字符。
    • @FireFuro99 最后一点!!,几乎我使用过的每个网站都是开发人员试图巧妙地处理其输入,即使使用经过验证的 UI 工具包,如 JQueryUI 等,它们通常最终成为使用起来最尴尬的网站,尤其是在移动设备上。在您的情况下,可能有一个很好的理由,但这只是需要注意的事情。
    【解决方案3】:

    这是一个使用 HTML 和 vanilla JS 的解决方案:

    function setInputFilter(textbox, inputFilter) {
      ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
        textbox.addEventListener(event, function() {
          if (inputFilter(this.value)) {
            this.oldValue = this.value;
            this.oldSelectionStart = this.selectionStart;
            this.oldSelectionEnd = this.selectionEnd;
          } else if (this.hasOwnProperty("oldValue")) {
            this.value = this.oldValue;
            this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
          } else {
            this.value = "";
          }
        });
      });
    }
    
    setInputFilter(document.getElementById("numTxtBox"), function(value) {
      return /^-?\d*$/.test(value); });
      &lt;tr&gt;&lt;td&gt;Number Only &lt;/td&gt;&lt;td&gt;&lt;input id="numTxtBox"&gt;&lt;/td&gt;&lt;/tr&gt;

    更新

    上述代码在 Firefox 和 Chrome 中确实出现故障。

    这是一个适用于所有浏览器的替代解决方案!

    function validate(num) {
      var theEvent = num || window.event;
    
      // Handle paste
      if (theEvent.type === 'paste') {
          var key = event.clipboardData.getData('text/plain');
      } else {
      // Handle key press
          var key = theEvent.keyCode || theEvent.which;
          key = String.fromCharCode(key);
      }
      var regex = /[0-9]|\./;
      if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
      }
    }
    &lt;input type='number' onkeypress='validate(event)' onpaste='validate(event)' /&gt;

    【讨论】:

    • 这不起作用。将&lt;input id="numTxtBox"&gt; 更改为&lt;input id="numTxtBox" type="number"&gt;(根据问题的要求),它将中断。
    • @FireFuro99 你什么意思?在这个例子中,它只允许插入整数,以及复制/粘贴/Ctrl+A?您不需要input type="number",因为这是一种解决方法。设置类型是多余的
    • input type="number" 是移动设备向用户建议数字键盘所必需的,而不是通常的字母键盘。这是问题的重点。请完整阅读问题。
    • 我的意思是“它坏了”,JS 代码不再起作用。在输入中添加 type="number" 后,您可以在输入中键入非数字字符。用火狐试试。 (Chrome 和 Edge 按标准阻止您在 type="number" 输入中输入非数字字符。Firefox 不会。)
    • 没注意到,谢谢指出!如果我的回答对您有帮助,请不要忘记将其标记为已接受!祝你有美好的一天
    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2014-09-14
    • 2013-08-05
    • 2018-03-06
    相关资源
    最近更新 更多