html keycodes not working in firefox

后端 未结 3 691
旧时难觅i
旧时难觅i 2021-01-21 18:59

I have the following code:

function noNumbers(e)
{
    var charCode = (e.which) ? e.which : 
                 ((e.charCode) ? e.charCode : 
                   ((         


        
3条回答
  •  梦谈多话
    2021-01-21 19:12

    Why not handle the input event instead? This method will handle live changes via keyboard entry, cut, paste, etc.

    (function() {
      var textBox = document.getElementById("text-box");
      textBox.addEventListener("input", function(e) {
        var val = this.value,
          rx = /[^\d]/g;
        if (rx.test(val)) {
          var pos = this.selectionStart;
          this.value = val.replace(rx, "");
          this.selectionStart = pos;
          this.selectionEnd = pos - 1;
        }
      });
    })();

提交回复
热议问题