Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html keycodes not working in firefox

I have the following code:

function noNumbers(e)
{
    var charCode = (e.which) ? e.which : 
                 ((e.charCode) ? e.charCode : 
                   ((e.keyCode) ? e.keyCode : 0));
    if((charCode < 48 || charCode > 57) && (charCode > 45 || charCode < 47))
        e.preventDefault();
}

The objective is to make it so that users can type numbers, the backspace key, and the delete key. It works in Chrome and IE, but in firefox, you can just type the numbers,not the backspace or delete keys however.

JSfiddle: https://jsfiddle.net/sdy9gd0g/

like image 729
user2072826 Avatar asked Jun 19 '26 21:06

user2072826


2 Answers

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>
like image 156
canon Avatar answered Jun 21 '26 11:06

canon


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">
like image 41
Dominic Avatar answered Jun 21 '26 09:06

Dominic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!