I wrote the following code (using jQuery) to show the pressed key.
$(window).keydown(function(e){
$("div").text("Key:" + String.fromCharCode(e.keyCode).toLowerCase());
return false;
});
This code works in normal alphabet characters (q,w,e,r…).
But when I press non alphabet keys (like ‘]’), an incorrect character is shown.
ex: ‘,’ -> ¼, ‘]’ -> ý
What’s wrong with my code?
Use the
keypressevent ande.whichproperty.jQuery normalizes the keycodes, and stores the variable in
event.which. Thekeypressevent’swhichproperty is the only reliable value forString.fromCharCode.The
event.keyCodeproperty may not be equal to theevent.charCodeorevent.whichproperties.For non-printable characters,
event.whichhas a value of zero, contrary toevent.keyCode. That’s why you’re seeing weird characters.