How to trigger a button click on keyboard "enter" with JavaScript?


To trigger a button click on keyboard "enter" with JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<h1>Trigger Button Click on Enter Example</h1>
<input id="inputField" value="Some text.." />
<button id="alertBtn" onclick="alert('Button has been clicked')">
Button
</button>
<h2>
Press the "Enter" key inside the above input field to trigger the button.
</h2>
<script>
   var inputText = document.getElementById("inputField");
   inputText.addEventListener("keyup", function(event) {
      if (event.keyCode === 13) {
         event.preventDefault();
         document.getElementById("alertBtn").click();
      }
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On typing something in the field and then pressing enter −

Updated on: 06-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements