jQuery Event Keypress: Which key was pressed?

832,613

Solution 1

Actually this is better:

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

Solution 2

Try this

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

Solution 3

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

Solution 4

Given that you are using jQuery, you should absolutely use .which. Yes different browsers set different properties, but jQuery will normalize them and set the .which value in each case. See documetation at http://api.jquery.com/keydown/ it states:

To determine which key was pressed, we can examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so we can reliably use it to retrieve the key code.

Solution 5

... this example prevents form submission (regularly the basic intention when capturing keystroke #13):

$('input#search').keypress(function(e) {
  if (e.which == '13') {
     e.preventDefault();
     doSomethingWith(this.value);
   }
});
Share:
832,613
Nishan
Author by

Nishan

Professional Web Developer since 2001, amateur developer since 198x. Eating and breathing JavaScript and PHP in my day-to-day live, but have seen a lot in my 30+ years of code-juggling. Adobe Certified Expert - Adobe Analytics Developer

Updated on July 08, 2022

Comments

  • Nishan
    Nishan almost 2 years

    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?