How to trigger button click by pressing Enter key

Use JavaScript to trigger button click by pressing "enter" key on the keyboard.

Trigger button click by pressing Enter key

Please press the "enter" key in the input box to trigger the button:

Instance

// Get the input field
var input = document.getElementById("myInput");
// The function executed when the user presses a key on the keyboard
input.addEventListener("keypress", function(event) {
  // If the user presses the Enter key on the keyboard
  if (event.key === "Enter") {
    // If necessary, cancel the default operation
    event.preventDefault();
    // Trigger the click event of the button element
    document.getElementById("myBtn").click();
  }
});

Try It Yourself

Related Pages

Reference Manual:KeyboardEvent key Property