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

后端 未结 30 2705
难免孤独
难免孤独 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:56

    Use keypress and event.key === "Enter" with modern JS!

    const textbox = document.getElementById("txtSearch");
    textbox.addEventListener("keypress", function onEvent(event) {
        if (event.key === "Enter") {
            document.getElementById("btnSearch").click();
        }
    });
    

    Mozilla Docs

    Supported Browsers

提交回复
热议问题