kdenney kdenney - 3 months ago 12
Javascript Question

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

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 inside the text box?

There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />


In jQuery, the following would work:

    if(event.keyCode == 13){

Or in plain JavaScript, the following would work:

    .addEventListener("keyup", function(event) {
    if (event.keyCode == 13) {