html keycodes not working in firefox

后端 未结 3 669
旧时难觅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;
        }
      });
    })();
    <input id="text-box" autofocus>

    0 讨论(0)
  • 2021-01-21 19:14

    You can simply add console.log(e); in your function and debug what's going on:

    Chrome/IE doesn't call this function on Backspace and Delete key press. Firefox logs keypress { target: <input#noNum>, key: "Backspace", charCode: 0, keyCode: 8 } and keypress { target: <input#noNum>, key: "Delete", charCode: 0, keyCode: 46 } respectively. So there is two solutions:

    1) Add if for these keyCodes (8 and 46)

    2) Do not use keypress event and use keydown instead (as @Teemu wrote).

    0 讨论(0)
  • 2021-01-21 19:28

    This works for me on Firefox.

    var keycodes = {
        'backspace': 8,
        'delete': 46,
        'leftArrow': 37,
        'rightArrow': 39,
        'number1': 48,
        'number9': 57
    };
    
    function noNumbers(e)
    {
        var charCode = e.which ? e.which : 
                     (e.charCode ? e.charCode : 
                       (e.keyCode ? e.keyCode : 0));
        
        if ((charCode < keycodes.number1 || charCode > keycodes.number9) &&
            charCode !== keycodes.delete &&
            charCode !== keycodes.backspace &&
            charCode !== keycodes.leftArrow &&
            charCode !== keycodes.rightArrow)
            e.preventDefault();
    }
    
    document.getElementById('noNum').addEventListener(
    	'keypress', noNumbers
    );
    <input id="noNum">

    0 讨论(0)
提交回复
热议问题