The DOM & EventsExtra· 35 min read

Handling Forms

Read what users type, validate it, and respond — without reloading the page.

What you will learn

  • Read form values in JavaScript
  • Prevent the default submit reload
  • Validate and respond

Read input and stop the reload

When a form submits, the page normally reloads. e.preventDefault() stops that so JavaScript can handle it instead.

Validate a form with JavaScript
<form id="signup">
  <input id="email" type="email" placeholder="Your email">
  <button type="submit">Join</button>
</form>
<p id="result"></p>

<script>
  document.getElementById("signup").addEventListener("submit", function(e) {
    e.preventDefault();                         // stop the reload
    const email = document.getElementById("email").value;
    if (email.includes("@")) {
      document.getElementById("result").textContent = "Thanks! We will email " + email;
    } else {
      document.getElementById("result").textContent = "Please enter a valid email.";
    }
  });
</script>
Live preview

Here is the whole flow, step by step, when the user clicks Join:

  1. The form fires a submit event, so our handler function runs.
  2. e.preventDefault() cancels the browser’s normal full-page reload, so we stay on the page.
  3. We read what the user typed with document.getElementById("email").value into email.
  4. We validate: email.includes("@") checks the text contains an "@" sign.
  5. If it passes, we show a thank-you message; if not, we show "Please enter a valid email."

Note: Output: Type "asha@mail.com" → Thanks! We will email asha@mail.com Type "asha" (no @) → Please enter a valid email.

Tip: This pattern — listen for submit, preventDefault, read .value, validate, respond — is exactly how login and signup forms work in real apps, including React.

Q. What does e.preventDefault() do on a form submit?

Answer: preventDefault() stops the browser’s default action (the full-page reload), letting JavaScript handle the submission.

✍️ Practice

  1. Build a form that greets the user by the name they type, without reloading.
  2. Validate that a field is not empty before showing a success message.

🏠 Homework

  1. Build a mini login form that checks a hard-coded username and password and shows a message.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →