jQuery normalizes e.which
, so you don't have to worry about this at all.
Also, it's a lot easier to just listen for the correct keycodes, there's no reason to convert the keycode to a character just to filter it out with indexOf
?
$('#foo').keydown(function(e) {
var code = e.which;
if (code == 8 || code == 13) return true; // backspace and enter
if (code < 48 || code > 57 || code == 188 || code == 190) return false;
});
FIDDLE
To keep most keys active, and just mainly disable characters, you could filter like this
$('#foo').keydown(function(e) {
var key = e.which;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
key >= 48 && key <= 57 || // numbers
key >= 96 && key <= 105 || // Numeric keypad
key == 190 || key == 188 || key == 109 || key == 110 || // comma, period and minus, . on keypad
key == 8 || key == 9 || key == 13 || // Backspace and Tab and EnterEnd
key == 35 || key == 36 || // Home and
key == 37 || key == 39 || // left and right arrows
key == 46 || key == 45) // Del and Ins
return true;
return false;
});
FIDDLE