javascript - Translate KeyDown keycode to string (jQuery) - Stack Overflow

I am looking for a way to translate a keypress into the string corresponding to the chracter. Something

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 0
Add a ment  | 

3 Answers 3

Reset to default 5

It'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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742383982a4433681.html

相关推荐

  • javascript - Translate KeyDown keycode to string (jQuery) - Stack Overflow

    I am looking for a way to translate a keypress into the string corresponding to the chracter. Something

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信