Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Event Keypress: Which key was pressed?

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?

like image 648
BlaM Avatar asked Nov 19 '08 14:11

BlaM


People also ask

How do you find out which key was pressed in jQuery?

To check whether user pressed ENTER key on webpage or on any input element, you can bind keypress or keydown event to that element or document object itself. Then in bind() function check the keycode of pressed key whether it's value is 13 is not.

What is keypress event in jQuery?

The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).

Which event is called when key is pressed?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .


2 Answers

Actually this is better:

 var code = e.keyCode || e.which;  if(code == 13) { //Enter keycode    //Do something  } 
like image 141
Eran Galperin Avatar answered Oct 05 '22 23:10

Eran Galperin


Try this

$('#searchbox input').bind('keypress', function(e) {     if(e.keyCode==13){         // Enter pressed... do anything here...     } }); 
like image 44
Vladimir Prudnikov Avatar answered Oct 06 '22 00:10

Vladimir Prudnikov