jQuery - Target button with enter key when input field is focused

后端 未结 5 1929
无人共我
无人共我 2021-02-01 04:33

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?<

5条回答
  •  深忆病人
    2021-02-01 05:03

    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();
        }
    });
    

提交回复
热议问题