I am looking for a way to translate a keypress into the string corresponding to the chracter. Something like this:
$(document).keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
except that this code does not take into account capitalization and does not work for special character, e.g. ",". This:
$(document).keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
seems to the trick, but it can not prevent default browser actions (such as go back on backspace) and there seem to be browser patibly issues.
Is there any better way, that works across browsers and keyboard layouts ?
I am looking for a way to translate a keypress into the string corresponding to the chracter. Something like this:
$(document).keydown(function(event) {
console.log(String.fromCharCode(event.which));
});
except that this code does not take into account capitalization and does not work for special character, e.g. ",". This:
$(document).keypress(function(event) {
console.log(String.fromCharCode(event.which));
});
seems to the trick, but it can not prevent default browser actions (such as go back on backspace) and there seem to be browser patibly issues.
Is there any better way, that works across browsers and keyboard layouts ?
Share Improve this question edited Nov 6, 2011 at 15:20 Maarten asked Nov 6, 2011 at 14:37 MaartenMaarten 4,7594 gold badges32 silver badges37 bronze badges 03 Answers
Reset to default 5It's not possible to reliably get the character from the event.which
property at an event type other than keypress
.
If you're questioning that statement, use the demo at this page. The event.which
property can only be translated correctly at a keypress
event.
If you want to ignore capitals, use the .toLowerCase()
method.
It is not surprising that keydown
event is not giving you upper case characters, since it is controlled by SHIFT key, which may or may not be pressed at the time.
To prevent default browser action simply return false from your handler.
What browser patibility issues are you having?
You can use same trick to get character code corresponding to key pressed. To prevent default browser actions you can try this-
event.preventDefault(); //For all major browsers
event.returnValue = false; //For Internet Explorer