In this article, we're going to see how to submit a form with the Enter key in JavaScript.
This solution is often useful in a very specific scenario: you have implemented an online chat and you want to allow users to send a form without clicking on a submit control.
Our solution is made up of two distinct parts: in the first, we intercept the submit
event on the form
element while in the second we add a keypress
event handler to the form control where users enter their text. In this part, we need to read the value of the code
property of the Event
object to make sure that users did actually press the Enter key. If so, we perform the action related to this event (for example, an AJAX call that sends to the server the text entered by users).
First, we need to prevent browsers from performing the default action associated with forms.
const handleSubmit = evt => {
return evt.preventDefault();
};
Then we have to define the action that is associated with the Enter key.
const enterAction = messageInput => {
document.getElementById('output').innerText = messageInput.value;
messageInput.value = '';
};
Finally, we need to intercept the Enter key.
const handleEnter = evt => {
if(evt.code === 'Enter') {
evt.preventDefault();
return enterAction(evt.target);
}
};
Last but not least, we can launch our code as follows:
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('form');
const message = document.getElementById('message');
form.addEventListener('submit', handleSubmit, false);
message.addEventListener('keypress', handleEnter, false);
}, false);