JavaScript Tutorial · JavaScript in the Browser · Lesson 43 of 44

JavaScript Forms

Read form values, validate input and handle submit events.

Handling submit

Listen for the form's submit event (not the button's click), call preventDefault() to handle it in JavaScript, and read the values with FormData:

Handle a form submitTry it yourself
<form id="signup" style="font-family: sans-serif; display: grid; gap: 8px; max-width: 280px">
  <input name="email" type="email" placeholder="Email" required>
  <input name="password" type="password" placeholder="Password (8+ chars)" required>
  <label><input name="newsletter" type="checkbox"> Send me news</label>
  <button>Sign up</button>
  <p id="msg"></p>
</form>
<script>
  document.getElementById("signup").addEventListener("submit", (event) => {
    event.preventDefault();
    const data = new FormData(event.target);
    const msg = document.getElementById("msg");
    if (data.get("password").length < 8) {
      msg.textContent = "Password must be at least 8 characters.";
      msg.style.color = "crimson";
      return;
    }
    msg.style.color = "green";
    msg.textContent = `Welcome, ${data.get("email")}! Newsletter: ${data.has("newsletter") ? "yes" : "no"}`;
  });
</script>

Validation

Start with HTML attributes — required, type="email", minlength, pattern — the browser checks them for free. Add JavaScript for rules HTML can't express, and always validate again on the server: client-side checks are for user experience, not security.

Storing data in the browser

localStorage keeps small strings between visits:

localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme") ?? "light";
localStorage.setItem("prefs", JSON.stringify({ fontSize: 16 }));

Test yourself

Where must you always validate form data, even if JavaScript validates it?

  1. In CSS
  2. On the server
  3. Nowhere else
  4. In localStorage
Show answer

Answer: On the server