How to Trigger Button Click on Enter Key Press using JavaScript

Generally, a form is submitted by clicking the button manually. But in some cases, the Enter key is required to be used along with the button to submit a form or an input field value. You can easily trigger a button by the Enter key press using JavaScript.

The keyCode property of the KeyboardEvent helps to track the key press on the keyboard using JavaScript. In this code snippet, we will show you how to trigger button click on Enter key press to submit a form using JavaScript.

The following example code, submit a form in both cases, manually button click and Enter key press on Keyboard.

  • Get the element of the input field.
  • Execute the keyup function with addEventListener when the user releases a key on the keyboard.
  • Check the number of the pressed key using JavaScript keyCode property.
  • If keyCode is 13, trigger button element with click() event.
    <input id="myInput" placeholder="Some text.." value="">
    <input type="submit" id="myBtn" value="Submit">

var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {

Note that: 13 is the number of the Enter key on the keyboard.

Related Articles

Comments 0