Submit a form with Enter key with JavaScript/jQuery
Problem statement: You have an HTML <form> without the submit button. How can you submit the form by pressing the Enter key using 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 submit the form. To determine the specific key that was pressed, you can use the event.which property. Now trigger the submit event on the form when you detect the Enter key.
jQuery
|
1 2 3 4 5 6 7 8 9 |
$(document).ready(function() { $('input').keyup(function(event) { if (event.which === 13) { event.preventDefault(); $('form').submit(); } }); }); |
HTML
|
1 2 3 4 |
<form> <label for="name">Enter your name: </label> <input type="text" name="name" id="name" required> </form> |
2. Using JavaScript
In vanilla JavaScript, you can bind an event handler to the keyup event using the addEventListener() method and use the KeyboardEvent.code property to determine whether an Enter key is pressed. Finally, trigger the form’s submit event on Enter keypress.
JS
|
1 2 3 4 5 6 7 8 |
document.getElementById('name') .addEventListener('keyup', function(event) { if (event.code === 'Enter') { event.preventDefault(); document.querySelector('form').submit(); } }); |
HTML
|
1 2 3 4 |
<form> <label for="name">Enter your name: </label> <input type="text" name="name" id="name" required> </form> |
That’s all about submitting a form with Enter key using 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 :)