5.3 Module 5 · Forms & Input Handling

Form Submission

Learn how to intercept form submission, prevent the default page reload, validate before sending, and build the complete submit flow that powers every login, registration, and contact form on the web.

1

Definition

Form Submission in JavaScript refers to the process of handling form data when a user submits a form — including controlling the default browser behaviour, validating inputs, displaying feedback, and optionally sending data to a server.

By default, submitting an HTML form causes the page to reload and sends data to the URL specified in the form's action attribute. In modern web apps we almost always intercept this with event.preventDefault() so JavaScript can validate and process the data first.

2

Simple Way

Form submission means "when the user clicks Submit → JavaScript decides what should happen". The typical flow:

onsubmit The event fired when any submit button inside a <form> is clicked
preventDefault Stop the browser from reloading the page — handle everything in JavaScript
validate Check all fields are correct before doing anything with the data
process Update the UI, show a success message, or send data to a server with fetch()
3

Code Examples

Example 1 — Without preventDefault (Page Reloads)
<form onsubmit="handleSubmit()">
  <input type="text" placeholder="Your name">
  <button type="submit">Submit</button>
</form>

<script>
  function handleSubmit() {
    console.log("Form submitted — but the page will reload!");
    // Without event.preventDefault(), the browser reloads the page
    // and your console.log disappears before you can see it
  }
</script>
Live Preview
Explanation
  • Without event.preventDefault(), the browser submits the form and reloads the page
  • Any changes made by your JavaScript handler are wiped out by the reload
  • In this preview the reload is contained to the iframe — in a real page your entire app state would be lost
Example 2 — With preventDefault (No Reload)
<form id="myForm">
  <input id="nameIn" type="text" placeholder="Your name">
  <button type="submit">Submit</button>
</form>
<p id="result"></p>

<script>
  document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault(); // stop the reload

    let name = document.getElementById("nameIn").value.trim();
    document.getElementById("result").textContent =
      name ? "Hello, " + name + "!" : "Please enter your name.";
  });
</script>
Live Preview
Explanation
  • addEventListener("submit", handler) — the preferred modern approach over inline onsubmit=""
  • event.preventDefault() must be called first, before any other logic
  • The page stays intact, the result is displayed without any reload
Example 3 — Validate → Then Process
<form id="sendForm">
  <input id="emailIn" type="text" placeholder="Email address">
  <button type="submit">Send</button>
</form>
<p id="sendResult"></p>

<script>
  document.getElementById("sendForm").addEventListener("submit", function(e) {
    e.preventDefault();

    let email = document.getElementById("emailIn").value.trim();
    let msg   = document.getElementById("sendResult");

    // Step 1: validate
    if (email === "") {
      msg.textContent  = "❌ Email is required.";
      msg.style.color  = "red";
      return; // stop — do not proceed
    }

    if (!email.includes("@")) {
      msg.textContent  = "❌ Enter a valid email address.";
      msg.style.color  = "red";
      return;
    }

    // Step 2: process (simulated)
    msg.textContent = "✓ Data received: " + email;
    msg.style.color = "green";
  });
</script>
Live Preview
Explanation
  • Use return after each error to exit early — no code below runs if validation fails
  • string.includes("@") is a simple email format check — production apps use regex
  • Only reach the processing step if every validation passes
Example 4 — Simulating a Data Send (fetch pattern)
// In real apps data is sent to a server with fetch()
// This example shows the pattern without a live server

function simulateSend(data) {
  return new Promise(function(resolve) {
    setTimeout(() => resolve({ ok: true, message: "Saved!" }), 800);
  });
}

async function handleFormSubmit(event) {
  event.preventDefault();

  let name = "Aman"; // would come from input.value in a real form

  let response = await simulateSend({ name: name });

  if (response.ok) {
    console.log("Server response:", response.message);
  }
}

// Simulate calling it
handleFormSubmit({ preventDefault: () => {} });
Output
Click ▶ Run — output appears after ~800ms
Explanation
  • Real form submissions use fetch(url, { method: "POST", body: JSON.stringify(data) })
  • async/await keeps the code readable while waiting for the server response
  • Always check response.ok before treating the submission as successful
4

Real-Life Example

Think of placing an order online — every step maps to the form submission flow:

onsubmit
You click "Place Order" — the submit event fires
preventDefault
"Wait — don't ship yet, let me verify the details first"
validate
System checks: address filled? card valid? quantity correct?
fetch / send
Order confirmed — the system sends data to the warehouse server
5

HTML + JavaScript Example

Click ▶ Preview — try submitting empty, with a wrong password, and with correct credentials to see the full validate-then-process flow.

Live in Browser — Login Form with Full Submission Flow
<!DOCTYPE html>
<html>
<head><title>Form Submission</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Login Form</h2>

  <form id="loginForm"
    style="display:flex;flex-direction:column;gap:10px;max-width:300px">

    <input id="userIn" type="text" placeholder="Username"
      style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;font-size:1rem">

    <input id="passIn" type="password" placeholder="Password"
      style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;font-size:1rem">

    <button type="submit"
      style="padding:9px;background:#f7df1e;border:none;border-radius:6px;
             cursor:pointer;font-weight:700;font-size:1rem">
      Login
    </button>
  </form>

  <p id="loginMsg" style="margin-top:14px;font-size:0.95rem"></p>

  <script>
    document.getElementById("loginForm").addEventListener("submit", function(e) {
      e.preventDefault();

      let user = document.getElementById("userIn").value.trim();
      let pass = document.getElementById("passIn").value.trim();
      let msg  = document.getElementById("loginMsg");

      // Validate
      if (user === "" || pass === "") {
        msg.textContent = "❌ Both fields are required.";
        msg.style.color = "red";
        return;
      }

      // Simulate authentication check
      if (user === "admin" && pass === "1234") {
        msg.textContent = "✓ Login successful! Welcome, " + user + ".";
        msg.style.color = "green";
      } else {
        msg.textContent = "❌ Invalid username or password.";
        msg.style.color = "red";
      }
    });
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Name submit with preventDefault
Starter code
<form id="nameForm">
  <input id="nameIn" type="text" placeholder="Your name">
  <button type="submit">Submit</button>
</form>

<script>
  document.getElementById("nameForm").addEventListener("submit", function(e) {
    // your code here
  });
</script>
  • Call e.preventDefault() to stop the reload
  • Read the name input and print it with console.log()
  • Clear the input field after printing by setting input.value = ""
Medium Task 2 — Login form with validation
Starter code
<form id="loginForm">
  <input id="user" type="text" placeholder="Username">
  <input id="pass" type="password" placeholder="Password">
  <button type="submit">Login</button>
</form>
<p id="lMsg"></p>
  • Prevent default, then check both fields are not empty
  • If either is empty → show "❌ All fields required" in red
  • Otherwise → show "✓ Login Successful" in green and clear both inputs
7

MCQs

Q1
What does event.preventDefault() do on a form submit?
<form id="f"><button type="submit">Go</button></form>
<script>
  document.getElementById("f").addEventListener("submit", function(e) {
    e.preventDefault();
    console.log("Handled — no reload!");
  });
</script>
Live Preview
  • A Submits the form to a server
  • B Reloads the page
  • C Stops the browser's default action (page reload)
  • D Deletes the form
💡 C is correct. event.preventDefault() cancels whatever the browser would have done by default. For a form submit that is reloading (or navigating to the action URL). After calling it, your JavaScript is fully in control.
Q2
Which event is triggered when a form is submitted?
  • A onclick
  • B submit
  • C onchange
  • D onload
💡 B is correct. The submit event fires on the <form> element when any type="submit" button inside it is clicked, or when Enter is pressed in an input field. Listen for it with form.addEventListener("submit", handler).
Q3
What happens if you do NOT call event.preventDefault() in a submit handler?
<form id="g"><button type="submit">Submit</button></form>
<script>
  document.getElementById("g").addEventListener("submit", function() {
    // no preventDefault here
    console.log("Runs... then page reloads");
  });
</script>
Live Preview
  • A Nothing changes — same as with preventDefault
  • B The form stops working
  • C The page reloads after the handler runs
  • D The form data is deleted
💡 C is correct. Without preventDefault(), the browser runs your handler and then continues with its default behaviour — reloading the page. Any DOM changes or messages you set get wiped out by the reload.
8

Pro Tips & Extra Knowledge

  • 01

    Always use addEventListener("submit", ...) on the form element — not onclick on the button — so that Enter key submission also triggers your handler:

    Attach to form, not the button
    // ✗ Misses Enter key — only fires on button click
    document.querySelector("button").addEventListener("click", handler);
    
    // ✓ Catches all submission paths — button click AND Enter key
    document.querySelector("form").addEventListener("submit", function(e) {
      e.preventDefault();
      handler();
    });
    Output
    Click ▶ Run to execute
  • 02

    Always validate before sending data — a failed API call is more costly (server round-trip) than catching the error client-side first:

    Validate → send pattern
    function handleSubmit(e) {
      e.preventDefault();
    
      let name = document.querySelector("#name").value.trim();
    
      // Step 1: validate first
      if (name === "") {
        console.log("Error: name is required");
        return; // stop — don't reach the send step
      }
    
      // Step 2: only send if valid
      console.log("Valid — sending:", name);
      // fetch("/api/submit", { method: "POST", body: JSON.stringify({ name }) });
    }
    Output
    Click ▶ Run to execute
  • 03

    Reset the form after a successful submission using form.reset() — it clears all inputs and checkboxes back to their default state:

    form.reset() after success
    let form = document.querySelector("form");
    
    form.addEventListener("submit", function(e) {
      e.preventDefault();
    
      let name = document.querySelector("#nameIn").value.trim();
      if (!name) return;
    
      console.log("Submitted:", name);
      form.reset(); // clears all fields — user sees a blank form
      console.log("Form reset — ready for next entry");
    });
    Output
    Click ▶ Run to execute
  • 04

    In production always pair client-side validation with server-side validation — JavaScript runs in the browser and can be disabled or bypassed. Never trust only frontend checks for security-sensitive data.

Mini Challenge

A type="submit" button is inside a <form> with no handler — will the page reload when you click it?

Will clicking this button reload the page?
<form>
  <button type="submit">Click</button>
</form>
Live Preview
Step-by-Step Explanation
// The form has no action attribute and no JavaScript handler

// When the button is clicked:
//   1. The browser fires the "submit" event on the form
//   2. No JavaScript handler intercepts it (no addEventListener, no onsubmit)
//   3. The browser falls through to its DEFAULT behaviour

// Default form behaviour:
//   → Submit the form to the current URL (same page, GET request)
//   → The page RELOADS

// In the preview iframe you will see it reload — watch the content blink.
// In a real full-page app this means losing all JavaScript state.

// Answer: YES — the page will reload.

// Fix: add a submit handler with preventDefault():
//
//   document.querySelector("form").addEventListener("submit", function(e) {
//     e.preventDefault();
//     console.log("Handled — no reload!");
//   });