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?
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.
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).
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 .
Actually this is better:
var code = e.keyCode || e.which; if(code == 13) { //Enter keycode //Do something }
Try this
$('#searchbox input').bind('keypress', function(e) { if(e.keyCode==13){ // Enter pressed... do anything here... } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With