CodeMIRAI
0 XP

Working with forms

2 min read 3 runnable examples Quiz included

Reading values

HTML
<input id="name" value="Asha">
<input id="age" type="number" value="21">
<input id="agree" type="checkbox" checked>
<select id="course"><option>Python</option><option selected>SQL</option></select>
<button id="read">Read values</button>

<script>
  document.querySelector("#read").addEventListener("click", () => {
    const name = document.querySelector("#name").value;
    const age = Number(document.querySelector("#age").value);   // .value is always a string
    const agreed = document.querySelector("#agree").checked;
    const course = document.querySelector("#course").value;
    console.log({ name, age, agreed, course });
  });
</script>

Handling submit

Listen for submit on the form (not click on the button), so pressing Enter works too, and call preventDefault() to stop the page reloading:

HTML
<form id="signup">
  <input name="email" type="email" placeholder="you@example.com" required>
  <input name="password" type="password" placeholder="Password (8+ characters)">
  <button>Create account</button>
</form>
<p id="msg"></p>

<script>
  const form = document.querySelector("#signup");
  const msg = document.querySelector("#msg");

  form.addEventListener("submit", (e) => {
    e.preventDefault();
    const data = new FormData(form);
    const email = data.get("email");
    const password = data.get("password");

    if (password.length < 8) {
      msg.textContent = "Password must be at least 8 characters.";
      msg.style.color = "crimson";
      return;
    }
    msg.textContent = `Welcome aboard, ${email}!`;
    msg.style.color = "green";
    form.reset();
  });
</script>

FormData collects every named field of the form in one go.

Live feedback while typing

HTML
<label>Username: <input id="user" maxlength="20"></label>
<p id="hint" style="font-family: system-ui; font-size: 14px"></p>

<script>
  const input = document.querySelector("#user");
  const hint = document.querySelector("#hint");

  input.addEventListener("input", () => {
    const v = input.value;
    if (!v) hint.textContent = "";
    else if (!/^[a-z0-9_]+$/i.test(v)) hint.textContent = "Only letters, numbers and _ please";
    else hint.textContent = `Looks good (${v.length}/20)`;
  });
</script>

Built-in validation first

HTML attributes such as required, type="email", minlength and pattern let the browser validate before your code runs (see the HTML forms lessons). Use JavaScript for the rules HTML can't express, like "passwords must match".

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.