jQuery Event Keypress: Which key was pressed?
Asked Answered
N

24

741

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?

Narration answered 19/11, 2008 at 14:59 Comment(9)
or you can use this: github.com/jeresig/jquery.hotkeys :)Wheeled
** If anyone has reached this from Google (like I did), know that "keyup" instead of "keypress" works in Firefox, IE, and Chrome. "keypress" apparently only works in Firefox.Querulous
also, "keydown" works better than "keyup" for triggering an event AFTER the key has been pressed (obviously) but this is important if you say want to trigger an event on the SECOND backspace if a textarea is emptyQuerulous
As for e.keyCode VS e.which... From my tests, Chrome and IE8: the keypress() handler will only get triggered for normal characters (i.e. not Up/Down/Ctrl), and both e.keyCode and e.which will return the ASCII code. In Firefox however, all keys will trigger keypress(), BUT: for normal characters e.which will return the ASCII code and e.keyCode will return 0, and for special characters (e.g. Up/Down/Ctrl) e.keyCode will return the keyboard code, and e.which will return 0. How fun.Bartko
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): 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.Translucent
"keyup" will get triggered very very late when you e.g. press a key for a long time. See here jsbin.com/aquxit/3/edit so keydown is the way to goCockatrice
Anyone still coming here for answers... this question is totally out of date. You want to use KeyboardEvent instead: developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCanale
@Cockatrice Actually no! keyup is triggered when you let the key go (on your keyboard) , as long as you hold the key it will not trigger. keydown triggers when key (on your keyboard is down). keyboard however will still send keypress as long as you are holding key (due to repeat function) but neither keyup or keydown will be triggered.Lactiferous
@ringo, does that article show how to use bind key event in jquery keypress event?Lactiferous
F
873

Actually this is better:

 var code = e.keyCode || e.which;
 if(code == 13) { //Enter keycode
   //Do something
 }
Fleck answered 19/11, 2008 at 15:7 Comment(2)
if ((e.keyCode || e.which) == 13) ? ;)Alienism
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.Eastman
N
139

Try this

$('#searchbox input').bind('keypress', function(e) {
    if(e.keyCode==13){
        // Enter pressed... do anything here...
    }
});
Nofretete answered 19/11, 2008 at 15:5 Comment(0)
C
61

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
Carburize answered 19/11, 2008 at 16:22 Comment(2)
Correction it's *$.ui.keyCode.ENTER** not *$.keyCode.ENTER -- does work like a charm though thx for the tip!Degroot
Uncaught TypeError: String.charCodeAt is not a function I think you meant to say '\r'.charCodeAt(0) == 13Sceptic
H
41

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.

Hithermost answered 5/3, 2010 at 17:47 Comment(2)
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.Potence
Do you have a repro that demonstrates this bug? Its preferable to report this to the owners of jQuery rather than try to reimplement their work.Hithermost
T
32

... 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);
   }
});
Tar answered 12/5, 2010 at 22:58 Comment(0)
P
28
 // in jquery source code...
 if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode)) {
     event.which = event.charCode || event.keyCode;
 }

 // So you have just to use
 $('#searchbox input').bind('keypress', function(e) {
     if (e.which === 13) {
         alert('ENTER WAS PRESSED');
     }
 });
Precocious answered 7/5, 2010 at 15:35 Comment(8)
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 .)Preliminaries
This is a direct paste from the jQuery source, and is the code that jQuery uses to normalize the .which event property.Coulombe
@Ian Clelland: i can't understand your point, is this working right or not!? lolPrecocious
It does work; I'm sure of it, because jQuery uses exactly that code :) If you already have jQuery available, then just use it -- you don't need to have this in your own code.Coulombe
@Ian Clelland: So why the OP is aking the question if he's already using jQuery?Precocious
@aSeptik: The question was "I have jQuery; how do I get the key pressed" -- your answer shows how jQuery gets it in the first place. My point was that since jQuery already contains this line of code, he doesn't need it. He can just use event.which.Coulombe
@Ian Clelland: why the accepted answer is almost the same of mine?Precocious
@aSeptik I can't speak for Ian, but one good reason might be that if the OP uses jQuery and updatse, he/she automagically gets the benefit of any improvements that can be made to that snippet, of which the jQuery team is aware and the OP is not.Pterous
B
27

edit: This only works for IE...

I realize this is an old posting, but someone might find this useful.

The key events are mapped, so instead of using the keycode value you can also use the key value to make it a little more readable.

$(document).ready( function() {
    $('#searchbox input').keydown(function(e)
    {
     setTimeout(function ()
     { 
       //rather than using keyup, you can use keydown to capture 
       //the input as it's being typed.
       //You may need to use a timeout in order to allow the input to be updated
     }, 5);
    }); 
    if(e.key == "Enter")
    {
       //Enter key was pressed, do stuff
    }else if(e.key == "Spacebar")
    {
       //Spacebar was pressed, do stuff
    }
});

Here is a cheat sheet with the mapped keys which I got from this blog enter image description here

Barrator answered 8/1, 2013 at 1:27 Comment(2)
There is no e.key property.Indefeasible
Hmm, it looks like it's an IE specific property. It works for my app in IE but not Chrome. Guess I'm using keycode.Barrator
P
23

This is pretty much the complete list of keyCodes:

3: "break",
8: "backspace / delete",
9: "tab",
12: 'clear',
13: "enter",
16: "shift",
17: "ctrl",
18: "alt",
19: "pause/break",
20: "caps lock",
27: "escape",
28: "conversion",
29: "non-conversion",
32: "spacebar",
33: "page up",
34: "page down",
35: "end",
36: "home ",
37: "left arrow ",
38: "up arrow ",
39: "right arrow",
40: "down arrow ",
41: "select",
42: "print",
43: "execute",
44: "Print Screen",
45: "insert ",
46: "delete",
48: "0",
49: "1",
50: "2",
51: "3",
52: "4",
53: "5",
54: "6",
55: "7",
56: "8",
57: "9",
58: ":",
59: "semicolon (firefox), equals",
60: "<",
61: "equals (firefox)",
63: "ß",
64: "@ (firefox)",
65: "a",
66: "b",
67: "c",
68: "d",
69: "e",
70: "f",
71: "g",
72: "h",
73: "i",
74: "j",
75: "k",
76: "l",
77: "m",
78: "n",
79: "o",
80: "p",
81: "q",
82: "r",
83: "s",
84: "t",
85: "u",
86: "v",
87: "w",
88: "x",
89: "y",
90: "z",
91: "Windows Key / Left ⌘ / Chromebook Search key",
92: "right window key ",
93: "Windows Menu / Right ⌘",
96: "numpad 0 ",
97: "numpad 1 ",
98: "numpad 2 ",
99: "numpad 3 ",
100: "numpad 4 ",
101: "numpad 5 ",
102: "numpad 6 ",
103: "numpad 7 ",
104: "numpad 8 ",
105: "numpad 9 ",
106: "multiply ",
107: "add",
108: "numpad period (firefox)",
109: "subtract ",
110: "decimal point",
111: "divide ",
112: "f1 ",
113: "f2 ",
114: "f3 ",
115: "f4 ",
116: "f5 ",
117: "f6 ",
118: "f7 ",
119: "f8 ",
120: "f9 ",
121: "f10",
122: "f11",
123: "f12",
124: "f13",
125: "f14",
126: "f15",
127: "f16",
128: "f17",
129: "f18",
130: "f19",
131: "f20",
132: "f21",
133: "f22",
134: "f23",
135: "f24",
144: "num lock ",
145: "scroll lock",
160: "^",
161: '!',
163: "#",
164: '$',
165: 'ù',
166: "page backward",
167: "page forward",
169: "closing paren (AZERTY)",
170: '*',
171: "~ + * key",
173: "minus (firefox), mute/unmute",
174: "decrease volume level",
175: "increase volume level",
176: "next",
177: "previous",
178: "stop",
179: "play/pause",
180: "e-mail",
181: "mute/unmute (firefox)",
182: "decrease volume level (firefox)",
183: "increase volume level (firefox)",
186: "semi-colon / ñ",
187: "equal sign ",
188: "comma",
189: "dash ",
190: "period ",
191: "forward slash / ç",
192: "grave accent / ñ / æ",
193: "?, / or °",
194: "numpad period (chrome)",
219: "open bracket ",
220: "back slash ",
221: "close bracket / å",
222: "single quote / ø",
223: "`",
224: "left or right ⌘ key (firefox)",
225: "altgr",
226: "< /git >",
230: "GNOME Compose Key",
231: "ç",
233: "XF86Forward",
234: "XF86Back",
240: "alphanumeric",
242: "hiragana/katakana",
243: "half-width/full-width",
244: "kanji",
255: "toggle touchpad"
Punctuation answered 6/8, 2017 at 16:55 Comment(0)
P
21

Checkout the excellent jquery.hotkeys plugin which supports key combinations:

$(document).bind('keydown', 'ctrl+c', fn);
Periclean answered 20/7, 2010 at 19:21 Comment(0)
W
14
$(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!!!

Whitted answered 17/2, 2009 at 11:18 Comment(0)
R
8

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

Rayerayfield answered 5/3, 2010 at 17:41 Comment(1)
This is absolutely the page that everyone floundering around providing hopeless answers should be reading.Leisure
N
7

Okay, I was blind:

e.which

will contain the ASCII code of the key.

See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which

Narration answered 19/11, 2008 at 15:1 Comment(0)
N
7

Use event.key and modern JS!

No number codes anymore. You can check key directly. For example "Enter", "LeftArrow", "r", or "R".

const input = document.getElementById("searchbox");
input.addEventListener("keypress", function onEvent(event) {
    if (event.key === "Enter") {
        // Submit
    }
    else if (event.key === "Q") {
        // Play quacking duck sound, maybe...
    }
});

Mozilla Docs

Supported Browsers

Nicholnichola answered 18/2, 2018 at 19:24 Comment(0)
A
5

I'll just supplement solution code with this line e.preventDefault();. In case of input field of form we don't attend to submit on enter pressed

var code = (e.keyCode ? e.keyCode : e.which);
 if(code == 13) { //Enter keycode
   e.preventDefault();
   //Do something
 }
Aerosol answered 10/2, 2012 at 19:59 Comment(0)
I
4

Add hidden submit, not type hidden, just plain submit with style="display:none". Here is an example (removed unnecessary attributes from code).

<form>
  <input type="text">
  <input type="submit" style="display:none">
</form>

it will accept enter key natively, no need for JavaScript, works in every browser.

Illa answered 19/4, 2011 at 14:54 Comment(0)
G
4

Witch ;)

/*
This code is for example. In real life you have plugins like :
https://code.google.com/p/jquery-utils/wiki/JqueryUtils
https://github.com/jeresig/jquery.hotkeys/blob/master/jquery.hotkeys.js
https://github.com/madrobby/keymaster
http://dmauro.github.io/Keypress/

http://api.jquery.com/keydown/
http://api.jquery.com/keypress/
*/

var event2key = {'97':'a', '98':'b', '99':'c', '100':'d', '101':'e', '102':'f', '103':'g', '104':'h', '105':'i', '106':'j', '107':'k', '108':'l', '109':'m', '110':'n', '111':'o', '112':'p', '113':'q', '114':'r', '115':'s', '116':'t', '117':'u', '118':'v', '119':'w', '120':'x', '121':'y', '122':'z', '37':'left', '39':'right', '38':'up', '40':'down', '13':'enter'};

var documentKeys = function(event) {
    console.log(event.type, event.which, event.keyCode);

    var keycode = event.which || event.keyCode; // par exemple : 112
    var myKey = event2key[keycode]; // par exemple : 'p'

    switch (myKey) {
        case 'a':
            $('div').css({
                left: '+=50'
            });
            break;
        case 'z':
            $('div').css({
                left: '-=50'
            });
            break;
        default:
            //console.log('keycode', keycode);
    }
};

$(document).on('keydown keyup keypress', documentKeys);

Demo : http://jsfiddle.net/molokoloco/hgXyq/24/

Geer answered 14/7, 2011 at 15:37 Comment(0)
H
4

Here's a jquery extension that will handle the enter key being pressed.

(function ($) {
    $.prototype.enterPressed = function (fn) {
        $(this).keyup(function (e) {
            if ((e.keyCode || e.which) == 13) {
                fn();
            }
        });
    };
}(jQuery || {}));

$("#myInput").enterPressed(function() {
    //do something
});

A working example can be found here http://jsfiddle.net/EnjB3/8/

Howund answered 12/10, 2012 at 16:36 Comment(0)
S
3
$(document).bind('keypress', function (e) {
    console.log(e.which);  //or alert(e.which);

});

you should have firbug to see a result in console

Skyrocket answered 17/11, 2011 at 11:7 Comment(0)
P
3

Some browsers use keyCode, others use which. If you're using jQuery, you can reliably use which as jQuery standardizes things. Actually,

$('#searchbox input').bind('keypress', function(e) {
    if(e.keyCode==13){

    }
});
Perni answered 8/5, 2014 at 11:34 Comment(0)
P
2

According to Kilian's answer:

If only enter key-press is important:

<form action="javascript:alert('Enter');">
<input type=text value="press enter">
</form>
Puett answered 14/9, 2011 at 10:37 Comment(0)
G
2

The easiest way that I do is:

$("#element").keydown(function(event) {
    if (event.keyCode == 13) {
        localiza_cep(this.value);
    }
});
Gareth answered 16/12, 2011 at 13:51 Comment(1)
It would be better to use event.which instead of event.keyCode. From jQuery API: The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input. Uninterested
T
2

I have just made a plugin for jQuery that allows easier keypress events. Instead of having to find the number and put it in, all you have to do is this:

How to use it

  1. Include the code I have below
  2. Run this code:
$(document).keydown(function(e) {
    if (getPressedKey(e) == theKeyYouWantToFireAPressEventFor /*Add 'e.ctrlKey here to only fire if the combo is CTRL+theKeyYouWantToFireAPressEventFor'*/) {
        // Your Code To Fire When You Press theKeyYouWantToFireAPressEventFor 
    }
});

It's that simple. Please note that theKeyYouWantToFireAPressEventFor is not a number, but a string (e.g "a" to fire when A is pressed, "ctrl" to fire when CTRL (control) is pressed, or, in the case of a number, just 1, no quotes. That would fire when 1 is pressed.)

The Example/Code:

function getPressedKey(e){var a,s=e.keyCode||e.which,c=65,r=66,o=67,l=68,t=69,f=70,n=71,d=72,i=73,p=74,u=75,h=76,m=77,w=78,k=79,g=80,b=81,v=82,q=83,y=84,j=85,x=86,z=87,C=88,K=89,P=90,A=32,B=17,D=8,E=13,F=16,G=18,H=19,I=20,J=27,L=33,M=34,N=35,O=36,Q=37,R=38,S=40,T=45,U=46,V=91,W=92,X=93,Y=48,Z=49,$=50,_=51,ea=52,aa=53,sa=54,ca=55,ra=56,oa=57,la=96,ta=97,fa=98,na=99,da=100,ia=101,pa=102,ua=103,ha=104,ma=105,wa=106,ka=107,ga=109,ba=110,va=111,qa=112,ya=113,ja=114,xa=115,za=116,Ca=117,Ka=118,Pa=119,Aa=120,Ba=121,Da=122,Ea=123,Fa=114,Ga=145,Ha=186,Ia=187,Ja=188,La=189,Ma=190,Na=191,Oa=192,Qa=219,Ra=220,Sa=221,Ta=222;return s==Fa&&(a="numlock"),s==Ga&&(a="scrolllock"),s==Ha&&(a="semicolon"),s==Ia&&(a="equals"),s==Ja&&(a="comma"),s==La&&(a="dash"),s==Ma&&(a="period"),s==Na&&(a="slash"),s==Oa&&(a="grave"),s==Qa&&(a="openbracket"),s==Ra&&(a="backslash"),s==Sa&&(a="closebracket"),s==Ta&&(a="singlequote"),s==B&&(a="ctrl"),s==D&&(a="backspace"),s==E&&(a="enter"),s==F&&(a="shift"),s==G&&(a="alt"),s==H&&(a="pause"),s==I&&(a="caps"),s==J&&(a="esc"),s==L&&(a="pageup"),s==M&&(a="padedown"),s==N&&(a="end"),s==O&&(a="home"),s==Q&&(a="leftarrow"),s==R&&(a="uparrow"),s==S&&(a="downarrow"),s==T&&(a="insert"),s==U&&(a="delete"),s==V&&(a="winleft"),s==W&&(a="winright"),s==X&&(a="select"),s==Z&&(a=1),s==$&&(a=2),s==_&&(a=3),s==ea&&(a=4),s==aa&&(a=5),s==sa&&(a=6),s==ca&&(a=7),s==ra&&(a=8),s==oa&&(a=9),s==Y&&(a=0),s==ta&&(a=1),s==fa&&(a=2),s==na&&(a=3),s==da&&(a=4),s==ia&&(a=5),s==pa&&(a=6),s==ua&&(a=7),s==ha&&(a=8),s==ma&&(a=9),s==la&&(a=0),s==wa&&(a="times"),s==ka&&(a="add"),s==ga&&(a="minus"),s==ba&&(a="decimal"),s==va&&(a="devide"),s==qa&&(a="f1"),s==ya&&(a="f2"),s==ja&&(a="f3"),s==xa&&(a="f4"),s==za&&(a="f5"),s==Ca&&(a="f6"),s==Ka&&(a="f7"),s==Pa&&(a="f8"),s==Aa&&(a="f9"),s==Ba&&(a="f10"),s==Da&&(a="f11"),s==Ea&&(a="f12"),s==c&&(a="a"),s==r&&(a="b"),s==o&&(a="c"),s==l&&(a="d"),s==t&&(a="e"),s==f&&(a="f"),s==n&&(a="g"),s==d&&(a="h"),s==i&&(a="i"),s==p&&(a="j"),s==u&&(a="k"),s==h&&(a="l"),s==m&&(a="m"),s==w&&(a="n"),s==k&&(a="o"),s==g&&(a="p"),s==b&&(a="q"),s==v&&(a="r"),s==q&&(a="s"),s==y&&(a="t"),s==j&&(a="u"),s==x&&(a="v"),s==z&&(a="w"),s==C&&(a="x"),s==K&&(a="y"),s==P&&(a="z"),s==A&&(a="space"),a}

$(document).keydown(function(e) {
  $("#key").text(getPressedKey(e));
  console.log(getPressedKey(e));
  if (getPressedKey(e)=="space") {
    e.preventDefault();
  }
  if (getPressedKey(e)=="backspace") {
    e.preventDefault();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>The Pressed Key: <span id=key></span></p>

Because the long version is so... well... long, I have made a PasteBin link for it:
http://pastebin.com/VUaDevz1

Tamratamsky answered 30/6, 2015 at 7:6 Comment(1)
You can make the function much shorter and faster if you don't use millions of "if" comparisons -> jsfiddle.net/BlaM/bcguctrx - Also be aware that - for example - openbracket and closebracket are not open/close brackets on a German keyboard`.Narration
E
2

The event.keyCode and event.which are deprecated. See @Gibolt answer above or check documentation: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

event.key should be used instead

keypress event is deprecated as well: https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

Effrontery answered 6/11, 2019 at 6:44 Comment(0)
I
-9

Try this:

jQuery('#myInput').keypress(function(e) {
    code = e.keyCode ? e.keyCode : e.which;
    if(code.toString() == 13) {
        alert('You pressed enter!');
    }
});
Ison answered 9/2, 2010 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.