Trigger Click Event on Enter Key Press Event using JavaScript

By | August 8, 2020

Whenever, we design and create a form, we often use a button to submit the form to save data in our database, however; in some special cases, we need to create a functionality to of saving data, when user press the ‘Enter’ button from his/her keyboard. By using a JavaScript event handler, we can easily trigger a button click event on enter keypress event.

JavaScript has a keyCode available for each key that exists in the keyboard. By using the JavaScript keyCode property, we will be tracking the keyCode of the ‘Enter’ key and then we will validate if it’s correct and then we will trigger the click event.

In the below code snippet, I will show you how to trigger the button click event on the ‘enter’ keypress event. Also, the keyCode of the ‘Enter’ key is 13. Here are the steps that we will follow:

  1. First, we will get the element ID of the input box
  2. Then, we will execute ‘keyup’ event by using JavaScript addEventListner() function
  3. And then, we will trigger the button’s click event. 
<html>  
<head> 
    <title>Trigger click event</title> 
 <head> 
  
 <body> 
 <b>Trigger click event<b>
 <div>
 <form>
	<p><input type="text" name="name" id="name" placeholder="Enter your name" />p>
	<p><input type="submit" name="submitbtn" id="submitbtn" value="Click me" />p>
 <form>
 <div>
    <script type="text/javascript"> 
		document.getElementById("name").addEventListener("keyup", function(e) {
			if (e.keyCode == 13) { /// keyCode of enter key is 13
				e.preventDefault();
				document.getElementById("submitbtn").click();
				alert('click event fired.');
			}
		});
<script>
<body> 
<html>

Form will look like:

trigger click event in javascript

Output:

trigger click event in javascript

Leave a Reply

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