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
A minor extension of Andrea's answer above makes the helper method more useful when you may also want to capture modified enter presses (i.e. ctrl-enter or shift-enter). For example, this variant allows binding like:
$('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')
to submit a form when the user presses ctrl-enter with focus on that form's textarea.
$.fn.enterKey = function (fnc, mod) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
fnc.call(this, ev);
}
})
})
}
(see also Ctrl+Enter jQuery in TEXTAREA)