views:

53797

answers:

13

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 an 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?

+2  A: 

Okay, I was blind:

e.which

will contain the ASCII code of the key.

See https://developer.mozilla.org/En/DOM/Event.which

BlaM
The link is broken.
Nathan Long
+14  A: 

Try this

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

Actually this is better:

 var code = (e.keyCode ? e.keyCode : e.which);
 if(code == 13) { //Enter keycode
   //Do something
 }
Eran Galperin
var code = e.keyCode || e.which;
Jimmy
if ((e.keyCode || e.which) == 13) ? ;)
Kezzer
According to a comment further down on this page, jQuery normalizes so that 'which' is defined on the event object every time. So, checking for 'keyCode' should be unnecessary.
Ztyx
Read the comment on that comment :)
Eran Galperin
Ionut Staicu's response is better for more general response.
Daniel Ribeiro
+9  A: 

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
Correction it's **$.ui.keyCode.ENTER** not *$.keyCode.ENTER* -- does work like a charm though thx for the tip!
MyWhirledView
+3  A: 

or you can use this: http://code.google.com/p/js-hotkeys/ :)

Ionut Staicu
Warning: DON'T use the one from google code. The author of jquery submited a patch, that is only on the github repository (and John Resig's fork as well): http://github.com/tzuryby/jquery.hotkeys.The one from google code misbehaves when binding more than one key event to the same dom node. The new one solves it.
Daniel Ribeiro
+4  A: 
$(document).ready(function(){
    $("#btnSubmit").bind("click",function(){$('#'+'<%=btnUpload.ClientID %>').trigger("click");return false;});
    $("body, input, textarea").keypress(function(e){
        if(e.which==13) $("#btnSubmit").click();
    });
});

Hope this may help you!!!

A: 

Try This:

jQuery('#myInput').keypress(function(e) {
  code = e.keyCode ? e.keyCode : e.which;
  if(code.toString() == 13) {
      alert('You pressed enter!');
  }
});

regards oyepez003

Omar Yepez
you're a necromancer, aren't you?
Gnark
+1  A: 

Here is an at-length description of the behaviour of various browsers http://unixpapa.com/js/key.html

Phil
+4  A: 

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.

Frank Schwieterman
From what I've seen using event.which and trying to compare to $.ui.keyCode results in uncertain behavior. Specifically the lowercase [L] key's which maps to $.ui.keyCode.NUMPAD_ENTER. Cute.
Danny
+3  A: 

this is probably the better and Comprehensive one!

really Cross-Browser way:

if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode: event.keyCode)) {
    event.which = event.charCode || event.keyCode;
}
aSeptik
This is the real answer. The accepted one will work for some keys (like enter) but will fail for others (like supr that will be mistaken by a .)
cad
This is a direct paste from the jQuery source, and is the code that jQuery uses to normalize the .which event property.
Ian Clelland
+2  A: 

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

$('input#search').keypress(function(e) {
  if (e.keyCode == '13') {
     e.preventDefault();
     doSomethingWith($('input#search').val());
   }
});
+2  A: 

Checkout this excellent jQuery hotkeys plugin which supports key combinations:

$(document).bind('keydown', 'ctrl+c', fn);
+1  A: 
$('*').keypress(function(e){
    // '0' means 'Escape' key
    // 'keyCode' or 'which' both are same       
    if(e.keyCode == 0 || e.keyCode == 27){
        alert('Yes');
    }
       else{
          alert('No');  
       }
    //this is for input text field
    $('#input_text').val(e.which)
});

Please This is not working in chrome browser.. any body tell me