Click a button by pressing Enter
How to trigger a click button pressing enter from an input using javascript

Overview

You may want to simulate a click on a button when the user presses the key 'Enter'.
It's an interesting functionality because:
  1. 1.
    It's good UX, as users often press Enter just after entering the data in the last field of a form, guessing that that action will trigger the expected action
  2. 2.
    Triggering the button click is the same as if the user were clicking it. This means that the conditions that apply to the button, apply to this 'javascript click' also, i.e. if there's a mandatory input empty, the button click won't be triggered.

Use cases

  • Trigger a login action when the user fills in the password field
  • Send a form when the user fills in the last form field
  • Etc.

Implementation

  1. 1.
    Assign an ID Attribute (in this example: password-login) to the input from where we expect the 'Enter' key would be pressed
  2. 2.
    Assign an ID Attribute (in this example: loginButton) to the button that we want to be clicked when the user presses 'Enter'
  3. 3.
    Put an HTML element in the page
  4. 4.
    Copy and paste the following code into the HTML element (make sure the IDs in the code match the input and login IDs):
<script>
//get the input
document.getElementById('password-login');
// add listener for keyup event
addEventListener('keyup', function(event) {
event.preventDefault();
// when the Enter key (13) is pressed, trigger a button click
if (event.keyCode === 13) {
document.getElementById('loginButton').click();
}
});
</script>
The HTML element
Copy link
On this page
Overview
Use cases
Implementation