Organizational Research By

Surprising Reserch Topic

How to detect pressing enter on keyboard using jquery?


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 it is the keypress command. http://docs.jquery.com/Events/keypress 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?

asked May 20, 2015 in JAVASCRIPT by rahulgii
0 votes
25 views



Related Hot Questions

3 Answers

0 votes
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).keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});
answered May 20, 2015 by rahulgii
0 votes
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!');
})
answered May 20, 2015 by rahulgii
0 votes

I found this to be more cross-browser compatible:

$(document).keypress(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13') {
        alert('You pressed a "enter" key in somewhere');    
    }
});

 

answered May 20, 2015 by rahulgii

...