Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

consistent keyCode for `#`

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();
        }
});

Fiddle for your pleasure.

like image 481
Christoph Avatar asked Jun 19 '13 09:06

Christoph


1 Answers

This works for me in Chrome and Firefox with a US keyboard:

$('[id$=txtClient]').keypress(function (e) {
    if (String.fromCharCode(e.which) == '#') {
        e.preventDefault();
    }
});

keypress is the only event that will give you reliable info on the character that was entered.

Demo: http://jsfiddle.net/elclanrs/ebcet/9/

like image 51
elclanrs Avatar answered Oct 12 '22 09:10

elclanrs