While I know that capturing keys due to the e.keyCode
vs e.charCode
is not trivial, I thought that jQuery would pretty much be able to normalize most of those inconsistencies.
However while answering this question I found out that the character #
seems to have very inconsistent keyCodes (and of course this is true for several other codes also, mostly depending on the browser and keyboardlayout I guess).
Chrome and IE yielded 191, Firefox 163 on my computer, another user reported 222. Chromes window.event
even reported U+00BF
as keyIdentifier - which according to unicode tables should be ¿
.
Do you know any consistent way to determine such symbols like the #
with inconsistent keyCodes without doing something nasty like the following:
$('input').keydown(function (e) {
if (e.which == 191 || e.which == 163 || e.which == 222){
// hope you got the right key
e.preventDefault();
}
});
Have you tried using the
keypress
event ?The documentation warns about possible differences in behavior between platforms.
In Firefox at least,
e.which
corresponds to the ascii code of the typed character after transformation :updated fiddle
This works for me in Chrome and Firefox with a US keyboard:
keypress
is the only event that will give you reliable info on the character that was entered.Demo: http://jsfiddle.net/elclanrs/ebcet/9/