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">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Trigger Button Click on Enter</title>
</head>
<body>
<input type="text" id="myInput">
<button id="myButton">Click me</button>
<script>
document.getElementById("myInput").addEventListener("keyup", function(event) {
if (event.key === "Enter") {
document.getElementById("myButton").click();
}
});
</script>
</body>
</html>
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
.