【问题标题】:Backspace not working in Firefox in input field退格在输入字段中的 Firefox 中不起作用
【发布时间】:2018-03-13 18:09:10
【问题描述】:

我将此输入与 onkeypress 事件一起提交:

<input type="number" min = "0" id = "count" onkeypress='return event.charCode >= 48 && event.charCode <= 57' /> 

基本上,这只允许在该字段中输入数字值......这很好用......在 Chrome、Firefox 和 IE 中......这对我来说已经足够了。但是“退格”键在 Firefox 中不起作用。它在 Chrome 和 IE 中运行良好。我的意思是,如果我想输入“15”,但不小心输入了“155”……在 Firefox 中,我无法在该字段上使用“退格”。如何让退格在 Firefox 中工作?

【问题讨论】:

标签: javascript html


【解决方案1】:

下面的 jQuery 代码 sn-ps 将只允许文本框中的数字。但是退格键和删除键也是允许的。

   $("#testID").keydown(function(e) {
    if (e.shiftKey)
     e.preventDefault();
    else {
     var nKeyCode = e.keyCode;
     //Ignore Backspace and Tab keys
     if (nKeyCode == 8 || nKeyCode == 9)

      return;

     if (nKeyCode < 95) {
      if (nKeyCode < 48 || nKeyCode > 57)
       e.preventDefault();
     } else {
      if (nKeyCode < 96 || nKeyCode > 105)
       e.preventDefault();
     }
    }
   });

【讨论】:

    【解决方案2】:

    您可以为 Backspace 键添加一个捕获:

    &lt;input type="number" min = "0" id = "count" onkeypress='return event.charCode &gt;= 48 &amp;&amp; event.charCode &lt;= 57 || event.key === "Backspace"' /&gt; 

    【讨论】:

      【解决方案3】:

      您可能想要这样做:

      var input = document.querySelector('#count');
      input.addEventListener('input', function (e) {
        return (e.keyCode === 8 || (e.keyCode >=48 && e.keyCode <=57));
      });
      &lt;input type="number" min="0" id="count"&gt;

      【讨论】:

      • 谢谢,但这允许我在该输入中输入我想要的任何值。我需要它只允许数字字符
      【解决方案4】:

      试试这个只允许数字的方法:

      function isNumber(evt) {
          evt = (evt) ? evt : window.event;
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode > 31 && (charCode < 48 || charCode > 57)) {
              return false;
          }
          return true;
      }
      &lt;input type="number" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" /&gt;

      https://jsfiddle.net/6dfrLz0p/12/

      【讨论】:

      • 谢谢@FirstLast 但onchange 允许用户输入非数字字符;(
      猜你喜欢
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2019-04-18
      相关资源
      最近更新 更多