I have an input field and a login button. I want to allow users to hit the \"enter\" key to click the button when the input field is focused. How would I do this with jQuery?<
The accepted answer, and most of the others, give for granted that the click() action might end event handling by submitting the form and switching to another page, or that there is not a submit somewhere on the form, so they omit stopping the event chain, but this might not be the case.
Don't forget to call e.preventDefault()
before calling click()
on the target button. Or else, the first button on the form will still fire on enter, in addition to your click!
$('#loginUserID').keypress(function(event) {
if(event.keyCode == 13) {
e.preventDefault(); // Stop the default behaviour
$('#loginBtn').click();
}
});