How to detect pressing Enter on keyboard using jQuery?
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!');
}
});
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