Victor Ferreira
Victor Ferreira

Reputation: 6449

String.fromCharCode on keypress and keydown are returning wrong characters

I'm trying to catch the character inserted before it shows on the screen to validate the screen. See my code

_this.on('keypress keydown',function(e){
    var t = e.target;
    var k = e.which || e.keyCode;
    var c = String.fromCharCode(k);
    console.log(String.fromCharCode(k))
});

If I for example type ~ or any other punctuation characters, it returns non-latin characters, such as å. I'm on Chromium, Ubuntu.

I noticed that the keypress is being ignored with these special characters, what is a shame and that's why I am trying with keydown as well. But keydown fails to detect the right character and converts them to scandinavian and asian characters.

Is there a workaround to get the correct character being yped?

Upvotes: 4

Views: 4367

Answers (1)

Anthony Hilyard
Anthony Hilyard

Reputation: 1240

See this wonderful answer to a similar question, and the associated jsfiddle: http://jsfiddle.net/S2dyB/17/

One problem is that the keypress and keydown events are not interchangeable. keypress is used to retrieve the actual character that was typed (so special keys are ignored), while keydown returns a unique character code for each key on the keyboard. To exacerbate this, different browsers handle each event a little bit differently, making it a big mess.

Take a look at how e.which varies between keydown and keypress: http://jsfiddle.net/9TyzP/

As you can see, they rarely match up--and with many keys, the displayed code for keypress doesn't change at all, indicating that the event did not fire for that key.

Upvotes: 3

Related Questions