Trigger a button click with JavaScript on the Enter key in a text box

后端 未结 30 2730
难免孤独
难免孤独 2020-11-21 23:53

I have one text input and one button (see below). How can I use JavaScript to trigger the button\'s click event when the Enter key is pressed ins

30条回答
  •  清歌不尽
    2020-11-22 00:31

    To do it with jQuery:

    $("#txtSearch").on("keyup", function (event) {
        if (event.keyCode==13) {
            $("#btnSearch").get(0).click();
        }
    });
    

    To do it with normal JavaScript:

    document.getElementById("txtSearch").addEventListener("keyup", function (event) {
        if (event.keyCode==13) { 
            document.getElementById("#btnSearch").click();
        }
    });
    

提交回复
热议问题