Trigger a button click on Enter key with JavaScript/jQuery
This post will discuss how to trigger a button click event on pressing the Enter key in JavaScript and jQuery.
1. Using jQuery
The idea is to bind an event handler to the keyup JavaScript event using jQuery’s .keyup(handler) method and use that handler to check for the Enter key. To determine the specific key which was pressed, you can use the event.which property. Now trigger the click event of the submit button when the Enter key is detected.
JS
|
1 2 3 4 5 6 7 8 9 10 11 |
$(document).ready(function() { $("#text").keyup(function(event) { if (event.which === 13) { $("#submit").click(); } }); $("#submit").click(function() { alert('clicked!'); }) }); |
HTML
|
1 2 |
<input id="text" type="text" placeholder="Enter your name…"> <button id="submit">Submit</button> |
2. Using JavaScript
In plain JavaScript, the idea remains similar. We bind an event handler to the keyup event using the addEventListener() method and use the KeyboardEvent.keyCode property to determine whether an Enter key is pressed. Finally, trigger the button click event on Enter keypress.
JS
|
1 2 3 4 5 6 7 8 9 10 |
document.getElementById("text") .addEventListener("keyup", function(e) { if (e.keyCode === 13) { document.getElementById("submit").click(); } }); document.getElementById("submit").onclick = function() { alert('Clicked!'); } |
HTML
|
1 2 |
<input id="text" type="text" placeholder="Enter your name…"> <button id="submit">Submit</button> |
Note that the keyCode attribute is no longer recommended; you should use the KeyboardEvent.code instead.
JS
|
1 2 3 4 5 6 7 8 9 10 |
document.getElementById("text") .addEventListener("keyup", function(e) { if (e.code === 'Enter') { document.getElementById("submit").click(); } }); document.getElementById("submit").onclick = function() { alert('Clicked!'); } |
HTML
|
1 2 |
<input id="text" type="text" placeholder="Enter your name…"> <button id="submit">Submit</button> |
Alternatively, you can use the onkeyup property, which is fired whenever a user releases the pressed key.
JS
|
1 2 3 4 5 6 7 8 9 |
function submitName(e) { if (e.code === 'Enter') { document.getElementById('submit').click(); } } document.getElementById("submit").onclick = function() { alert('Clicked!'); } |
HTML
|
1 2 3 |
<input id="text" type="text" placeholder="Enter your name…" onkeyup="return submitName(event);"> <button id="submit">Submit</button> |
That’s all about triggering a button click on Enter key in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)