Skip to content

JavaScript Tutorial Forms and Validation

Handling Form Submit in JavaScript

Lesson 123 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

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.

index.html
HTML
<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

script.js
JS
// 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)?

script.js
JS
form.addEventListener("submit", event => {
  console.log(event.submitter?.value);
});

Prevent double submits

When you send data to a server, disable the button while waiting.

index.html
HTML
<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

script.js
JS
form.requestSubmit();   // like clicking submit: runs validation and fires the submit event
form.submit();          // skips validation and the submit event

Prefer requestSubmit().

lightbulb
Server still matters
Handling a form in JavaScript is for a better experience. The server must still validate and secure the data, because JavaScript checks can be bypassed.