Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect pressing Enter on keyboard using jQuery?

I would like to detect whether the user has pressed Enter using jQuery.

How is this possible? Does it require a plugin?

EDIT: It looks like I need to use the keypress() method.

I wanted to know if anyone knows if there are browser issues with that command - like are there any browser compatibility issues I should know about?

like image 711
chris Avatar asked Jun 11 '09 06:06

chris


People also ask

How do you check Enter key is pressed in jQuery?

The “enter” key is represent by code “13”, check this ASCII charts. To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox').

How do you detect if Enter is pressed?

Check the event.The keyCode property returns a number for the key that's pressed instead of a string with the key name. When it returns 13, then we know the enter key is pressed.

How do you trigger click event on pressing Enter key?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.


2 Answers

I wrote a small plugin to make it easier to bind the "on enter key pressed" a event:

$.fn.enterKey = function (fnc) {     return this.each(function () {         $(this).keypress(function (ev) {             var keycode = (ev.keyCode ? ev.keyCode : ev.which);             if (keycode == '13') {                 fnc.call(this, ev);             }         })     }) } 

Usage:

$("#input").enterKey(function () {     alert('Enter!'); }) 
like image 29
Andrea Avatar answered Sep 27 '22 18:09

Andrea


The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

$(document).on('keypress',function(e) {     if(e.which == 13) {         alert('You pressed enter!');     } }); 
like image 190
Paolo Bergantino Avatar answered Sep 27 '22 18:09

Paolo Bergantino