Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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 −

Advertisements