CPCODELAB
JavaScript

Forms and User Input

8 min read

Working with Forms

Forms collect user data. JavaScript lets you read input values, validate them, and handle submission without reloading the page.

javascript
const form = document.querySelector("#signup-form");

form.addEventListener("submit", (e) => {
  e.preventDefault(); // stop the browser reload

  const data = new FormData(form);
  const name  = data.get("name");
  const email = data.get("email");

  if (!email.includes("@")) {
    showError("Invalid email address");
    return;
  }

  // Send data…
  console.log({ name, email });
});

// Reading individual inputs
const nameInput = document.querySelector("#name");
nameInput.value;        // current value
nameInput.placeholder;  // placeholder text

// Live input event
nameInput.addEventListener("input", () => {
  console.log("Typing:", nameInput.value);
});

Never trust user input. Always validate on the server, even if you validate in the browser first. Client-side validation is for UX only — it can be bypassed.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises