jQuery Event Keypress: Which key was pressed?

04/07/2020 10:00:01

With jQuery, how do I find out which key was pressed when I bind to the keypress event?

$('#searchbox input').bind('keypress', function(e) {});

I want to trigger a submit when ENTER is pressed.

[Update]

Even though I found the (or better: one) answer myself, there seems to be some room for variation ;)

Is there a difference between keyCode and which - especially if I'm just looking for ENTER, which will never be a unicode key?

Do some browsers provide one property and others provide the other one?

Verified Answer (843 Votes)

11/19/2008 20:07:10

Actually this is better:

 var code = e.keyCode || e.which;
 if(code == 13) { //Enter keycode
   //Do something
 }
843

Answer #2 (132 Votes)

11/19/2008 20:05:29

Try this

$('#searchbox input').bind('keypress', function(e) {
    if(e.keyCode==13){
        // Enter pressed... do anything here...
    }
});
132

Answer #3 (61 Votes)

11/19/2008 21:22:34

If you are using jQuery UI you have translations for common key codes. In ui/ui/ui.core.js:

$.ui.keyCode = { 
    ...
    ENTER: 13, 
    ...
};

There's also some translations in tests/simulate/jquery.simulate.js but I could not find any in the core JS library. Mind you, I merely grep'ed the sources. Maybe there is some other way to get rid of these magic numbers.

You can also make use of String.charCodeAt and .fromCharCode:

>>> String.charCodeAt('\r') == 13
true
>>> String.fromCharCode(13) == '\r'
true
61
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.