JavaScript Trigger a button on ENTER key

To trigger a button on ENTER key, the code is as follows −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   .result {
      color: blueviolet;
<h1>Trigger a button on ENTER key</h1>
Enter text<input type="text" class="sample" />
<button class="Btn">CLICK HERE</button>
<div class="result"></div>
Press enter in the above text field to trigger the button
   let resultEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   sampleEle.addEventListener("keyup", (event) => {
      if (event.keyCode === 13) {
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML ="Button has been clicked and text = " + sampleEle.value;


On entering some text and pressing enter key in the input field −

Updated on: 12-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started