The DOM & Events›Extra· 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.
<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:
- The form fires a
submitevent, so our handler function runs. e.preventDefault()cancels the browser’s normal full-page reload, so we stay on the page.- We read what the user typed with
document.getElementById("email").valueintoemail. - We validate:
email.includes("@")checks the text contains an "@" sign. - 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
- Build a form that greets the user by the name they type, without reloading.
- Validate that a field is not empty before showing a success message.
🏠 Homework
- Build a mini login form that checks a hard-coded username and password and shows a message.