When a user presses Enter in a field or clicks a submit button, the browser submits the form. By default that reloads the page or navigates to the form’s action. To handle it with JavaScript, listen for the submit event and stop the default.
<form id="contact">
<label>Name <input name="name" required></label>
<label>Message <input name="message"></label>
<button type="submit">Send</button>
</form>
<p id="status" role="status"></p>
<script>
const form = document.querySelector("#contact");
form.addEventListener("submit", event => {
event.preventDefault(); // stay on the page
const name = form.elements.name.value.trim();
const message = form.elements.message.value.trim();
document.querySelector("#status").textContent = `Thanks ${name}! You wrote: ${message || "(nothing)"}`;
form.reset();
});
</script>
Listen to submit, not click
// Misses the Enter key, and ignores validation:
submitButton.addEventListener("click", ...);
// Works for mouse, keyboard and assistive technology:
form.addEventListener("submit", ...);
The submit event only fires when the form passes the browser’s built-in validation (like required), so you do not have to repeat it.
Do not forget preventDefault
If you leave it out, the page reloads and your result disappears. That is the most common reason a form “does nothing” in tutorials.
The submitter
Which button was pressed (when there are several)?
form.addEventListener("submit", event => {
console.log(event.submitter?.value);
});
Prevent double submits
When you send data to a server, disable the button while waiting.
<form id="f"><button id="send">Send</button></form>
<p id="out"></p>
<script>
const form = document.querySelector("#f");
const button = document.querySelector("#send");
form.addEventListener("submit", async event => {
event.preventDefault();
button.disabled = true;
button.textContent = "Sending…";
await new Promise(resolve => setTimeout(resolve, 800)); // pretend to talk to a server
document.querySelector("#out").textContent = "Sent!";
button.disabled = false;
button.textContent = "Send";
});
</script>
(async and await are covered in async and await.)
Submitting programmatically
form.requestSubmit(); // like clicking submit: runs validation and fires the submit event
form.submit(); // skips validation and the submit event
Prefer requestSubmit().