JavaScript Answers

How to trigger HTML button click when pressing Enter in a text box with JavaScript?

Spread the love

You can achieve this by adding an event listener to the text box to detect when the Enter key is pressed, and then triggering the click event of the HTML button.

For example, we write:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Trigger Button Click on Enter</title>

<input type="text" id="myInput">
<button id="myButton">Click me</button>

document.getElementById("myInput").addEventListener("keyup", function(event) {
  if (event.key === "Enter") {


In this example, we add an event listener to the text input with the id myInput.

When a key is pressed (keyup event), the function checks if the pressed key is “Enter”.

If “Enter” is pressed, it triggers a click event on the button with the id myButton.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *