JavaScript Trigger a button on ENTER key

JavascriptWeb DevelopmentObject Oriented Programming

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

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample,
   .result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
   .result {
      color: blueviolet;
   }
</style>
</head>
<body>
<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>
<h3>
Press enter in the above text field to trigger the button
</h3>
<script>
   let resultEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   sampleEle.addEventListener("keyup", (event) => {
      if (event.keyCode === 13) {
         event.preventDefault();
         document.querySelector(".Btn").click();
      }
   });
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML ="Button has been clicked and text = " + sampleEle.value;
   });
</script>
</body>
</html>

Output

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

raja
Published on 12-May-2020 09:35:51
Advertisements