Reputation: 79
I have to disable some symbols from html input.
e.which
is not working properly on Firefox. Firefox disables backspace
and ect.
Here is JS Fiddle:
var code = window.event ? event.keyCode : e.which;
event.keyCode
works on firefox, but does not work with String.fromCharCode(code)
.
Upvotes: 1
Views: 2060
Reputation: 318342
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;
});
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;
});
Upvotes: 2
Reputation: 29434
You've got two errors in your script:
event
but referred to e.which
.2. you have to call
evt.preventDefault()
for preventing the typed character to appear.
The latter point is wrong when adding jQuery event handlers. 'Normal' DOM handlers require preventDefault()
, see also this comment.
$('#foo').keypress(function(evt) {
var code = window.event ? event.keyCode : evt.which;
var chr = String.fromCharCode(code);
if ("0123456789.,".indexOf(chr) < 0) {
return false;
}
});
Upvotes: 0