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?


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!');
    }
});

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!');
})

I couldn't get the code posted by @Paolo Bergantino to work but when I changed it to $(document) and e.which instead of e.keyCode then I found it to work faultlessly.

$(document).keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

Link to example on JS Bin

链接地址: http://www.djcxy.com/p/50356.html

上一篇: 如何使用Obj C检测iPhone v iPhone 3G

下一篇: 如何检测使用jQuery在键盘上按Enter键?