1

I've written a very simple class selector so that I can make html input boxes only accept numeric inputs

$(".numericOnly").keypress(function (e) {
   if (e.keyCode == 13) return true;
   if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) 
      return false;     
});

Then, if you have an input box, you just assign it class="numericOnly" and it will only accept numeric input.

keyCode 13 is the enter key, which prevents the function from intercepting and blocking it.

It works great in Chrome and oddly in IE 9, but it fails in firefox. Not sure why. There are no errors being thrown.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Use `e.charCode` with Firefox. See here: http://stackoverflow.com/questions/6869996/jquery-keypress-event-object-keycode-for-firefox-problem – glortho Nov 10 '12 at 18:43

2 Answers2

1

The attribute name for the key that was pressed (keyCode or charCode) varies by browser. Try using event.which instead, which normalizes that for you.

Renato Zannon
  • 28,805
  • 6
  • 38
  • 42
1

keyCode is set in keydown and keyup handlers. charCode is set in keypress handlers, and indicates which character was entered (which is not the same thing as which key was pressed, because different keyboard layouts exist).

Boris Zbarsky
  • 34,758
  • 5
  • 52
  • 55