Skip to content

Lesson 23 of 50JavaScript in the browser

Forms in JavaScript

Handle form submits without a reload, read every field with FormData, and validate with clear, accessible error messages.

17 min read0/5 questions

Sign-up pages, checkouts, search boxes, settings screens: most of what people do on the web goes through a form. HTML already gives you a lot for free, including labels, keyboard support, and built-in checks like required. JavaScript takes over the parts HTML cannot do alone: sending the data without reloading the page, checks that compare two fields, and error messages that are clear and readable by screen readers. This lesson shows how to do that while keeping everything the browser gives you.

Listen for submit, not click

The most common beginner mistake is putting a click listener on the form's button. It seems to work, until someone presses Enter in a text field, which submits the form without touching the button. The right event is submit on the form element. It fires however the form is sent: a click on the submit button, Enter in a field, or a keyboard user pressing Space on the button.

By default, submitting a form makes the browser send the data to the URL in the form's action attribute and load a new page. To handle it in JavaScript instead, call event.preventDefault() first thing in the listener.

What happens when a form is submitted
UserBrowserYour codepresses Enter or Submitinvalid? shows a messagesubmit eventevent.preventDefault()read fields, update page

Any way of submitting starts the same process.

1/5
HTML & CSS
<style> form { display: flex; gap: 8px; align-items: end; flex-wrap: wrap; } label { display: grid; gap: 4px; } input, button { font: inherit; padding: 6px 10px; }</style> <h3>Get the weekly recipe</h3><form id="signup"> <label>Email <input type="email" name="email" required autocomplete="email"> </label> <button>Subscribe</button></form><p id="message" role="status"></p> <script> const form = document.getElementById("signup"); const message = document.getElementById("message"); form.addEventListener("submit", (event) => { event.preventDefault(); const email = form.elements.email.value; message.textContent = `Thanks! We will write to ${email}.`; form.reset(); });</script>

Preview

Try submitting with an empty box, then with maya@, then with a real-looking address. The first two never reach your code: the browser blocks them because of required and type="email". Press Enter instead of clicking and notice it still works. A button inside a form is a submit button unless you give it type="button".

Quick check
Why put your listener on the form's submit event rather than on the button's click event?
Need a nudge? A hint rules out a wrong answer.

Reading values

Every field has a value property holding its current contents. Two things catch people out:

  • value is always a string, even for type="number" and type="range". Convert with Number(input.value), or use input.valueAsNumber, which gives a number (or NaN if the box is empty).
  • For checkboxes, value is the fixed value from the HTML. Whether it is ticked is in checked, a boolean.

You can reach fields through form.elements, which lets you look them up by their name attribute: form.elements.email. For a group of radio buttons sharing a name, form.elements.size.value gives the value of the selected one.

Predict the outputJavaScript

What does this print?

const input = document.createElement("input");
input.type = "number";
input.value = "3";
console.log(input.value + 1);
Need a nudge? Hints walk you through it.

FormData: every field at once

Reading fields one by one gets tedious. new FormData(form) collects every field that has a name attribute into one object, using the same rules the browser uses when it sends a form:

  • data.get("name") returns the value of one field (a string, or a File for file inputs).
  • data.getAll("toppings") returns an array, for checkbox groups that share a name.
  • Object.fromEntries(data) turns it into a plain object. Careful: for repeated names it keeps only the last value, so use getAll for those.
  • Fields without a name, disabled fields, and unticked checkboxes are left out entirely.
HTML & CSS
<style> form { display: grid; gap: 10px; max-width: 360px; } fieldset { display: flex; gap: 12px; flex-wrap: wrap; } pre { background: #f4f4f5; padding: 10px; white-space: pre-wrap; }</style> <form id="order"> <label>Name <input name="name" value="Sam"></label> <fieldset> <legend>Size</legend> <label><input type="radio" name="size" value="small"> Small</label> <label><input type="radio" name="size" value="large" checked> Large</label> </fieldset> <fieldset> <legend>Toppings</legend> <label><input type="checkbox" name="toppings" value="olives" checked> Olives</label> <label><input type="checkbox" name="toppings" value="basil"> Basil</label> <label><input type="checkbox" name="toppings" value="peppers" checked> Peppers</label> </fieldset> <label>Quantity <input type="number" name="quantity" value="2" min="1" max="10"></label> <button>Place order</button></form><pre id="out">Submit the form to see the data.</pre> <script> const form = document.getElementById("order"); form.addEventListener("submit", (event) => { event.preventDefault(); const data = new FormData(form); const order = { ...Object.fromEntries(data), toppings: data.getAll("toppings"), quantity: Number(data.get("quantity")), }; document.getElementById("out").textContent = JSON.stringify(order, null, 2); });</script>

Preview

Submit it, then untick every topping and submit again: toppings becomes an empty array. Remove the name from the Name field and it vanishes from the output. Try deleting the toppings: line to see Object.fromEntries keep only one topping.

FormData is also what you send to a server. fetch accepts it directly as the body, which sends it the same way a normal form would (including files). If your API expects JSON instead, send the object you built:

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const button = form.querySelector("button");
  button.disabled = true; // stop double submits
 
  try {
    const response = await fetch("/api/orders", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(Object.fromEntries(new FormData(form))),
    });
    if (!response.ok) throw new Error(`Server said ${response.status}`);
    status.textContent = "Order placed.";
  } catch {
    status.textContent = "Something went wrong. Please try again.";
  } finally {
    button.disabled = false;
  }
});
Quick check
A form has a checkbox <input type=checkbox name=terms> that the user leaves unticked. What does new FormData(form).get('terms') return?
Need a nudge? A hint rules out a wrong answer.

Validation with the constraint API

HTML attributes give you a lot of validation for free: required, type="email", minlength, maxlength, min, max, step and pattern (a regular expression the value must match). Behind those attributes is the constraint validation API, which JavaScript can read and extend:

MemberWhat it does
field.validityAn object of true or false flags explaining what is wrong
field.validity.validtrue if every rule passes
field.validationMessageThe browser's message for the current problem, in the user's language
field.setCustomValidity("...")Mark the field invalid with your own message; pass "" to clear it
form.checkValidity()true if every field is valid, without showing anything
form.reportValidity()Same check, and shows the browser's messages

The validity flags map to the attributes: valueMissing (required), typeMismatch (type="email" or "url"), tooShort (minlength), patternMismatch (pattern), rangeUnderflow and rangeOverflow (min and max), and customError (you called setCustomValidity).

Match the pairs0/5 matched

Match each validity flag to the attribute that triggers it.

Choose an item, then its match on the other side.

setCustomValidity is how you add rules HTML cannot express, like "the two passwords must match". The catch: a custom error stays until you clear it with an empty string, so set it on every input event.

HTML & CSS
<style> form { display: grid; gap: 10px; max-width: 320px; } input { font: inherit; padding: 6px; }</style> <form id="account"> <label>Password <input type="password" name="password" minlength="8" required></label> <label>Confirm password <input type="password" name="confirm" required></label> <button>Create account</button></form><p id="result" role="status"></p> <script> const form = document.getElementById("account"); const { password, confirm } = form.elements; function checkMatch() { confirm.setCustomValidity( confirm.value && confirm.value !== password.value ? "The passwords do not match." : "" ); } password.addEventListener("input", checkMatch); confirm.addEventListener("input", checkMatch); form.addEventListener("submit", (event) => { event.preventDefault(); document.getElementById("result").textContent = "Account created."; });</script>

Preview

Type a short password and submit, then two different passwords. The browser shows your custom message in the same bubble as its own. Then change the final "" in checkMatch to "Still wrong", so the message is never cleared, and notice the form can never be submitted again even when the passwords match: that is the classic forgotten-clear bug.

Accessible error messages

The browser's bubbles are a fine start, but they disappear quickly, cannot be styled, and say little about the rule. Most real forms show their own messages next to each field. Doing that well means:

  1. Add novalidate to the form. That turns off the bubbles, but the constraint API still works, so you can keep using validity.
  2. Put an error element under each field and connect them with aria-describedby, so a screen reader reads the message when the field gets focus.
  3. Set aria-invalid="true" on fields with an error, and remove it once fixed.
  4. On a failed submit, move focus to the first invalid field.
  5. Write messages that say how to fix the problem: "Enter an email like name@example.com", not "Invalid input".
HTML & CSS
<style> form { display: grid; gap: 4px; max-width: 340px; } label { margin-top: 8px; font-weight: 600; } input { font: inherit; padding: 6px; border: 2px solid #999; } input[aria-invalid="true"] { border-color: #b91c1c; } .error { color: #b91c1c; font-size: 14px; min-height: 1.4em; margin: 0; } button { margin-top: 12px; font: inherit; padding: 6px; }</style> <form id="contact" novalidate> <label for="name">Name</label> <input id="name" name="name" required aria-describedby="name-error"> <p class="error" id="name-error"></p> <label for="email">Email</label> <input id="email" name="email" type="email" required aria-describedby="email-error"> <p class="error" id="email-error"></p> <button>Send</button></form><p id="done" role="status"></p> <script> const form = document.getElementById("contact"); const messages = { name: { valueMissing: "Enter your name." }, email: { valueMissing: "Enter your email address.", typeMismatch: "Enter an email like name@example.com.", }, }; function showError(field) { const error = document.getElementById(`${field.id}-error`); const rules = messages[field.name]; const problem = Object.keys(rules).find((flag) => field.validity[flag]); error.textContent = problem ? rules[problem] : ""; field.setAttribute("aria-invalid", String(Boolean(problem))); return !problem; } form.addEventListener("submit", (event) => { event.preventDefault(); const fields = [...form.querySelectorAll("input")]; const results = fields.map(showError); const firstBad = fields[results.indexOf(false)]; if (firstBad) { firstBad.focus(); document.getElementById("done").textContent = ""; return; } document.getElementById("done").textContent = "Message sent."; form.reset(); }); form.addEventListener("input", (event) => { if (event.target.getAttribute("aria-invalid") === "true") showError(event.target); });</script>

Preview

Submit the empty form: both messages appear and focus jumps to Name. Fix one field and its message clears as you type, because the last listener (delegated on the whole form) re-checks only fields already marked invalid. That is a good rhythm: do not shout at people while they are still typing, but clear the error the moment it is fixed.

The CSS pseudo-class :user-invalid can style fields red only after the user has interacted with them. It is supported in all current major browsers, but check MDN or Can I Use before relying on it for older ones.

Put it in order5 steps

Put the steps of a JavaScript submit handler in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
submit event
Fires on a form when it is sent by a button or the Enter key, after built-in validation passes.
FormData
An object holding every named, enabled field of a form, built with new FormData(form).
constraint validation API
The browser's validation system: validity, validationMessage, setCustomValidity, checkValidity, reportValidity.
setCustomValidity
Marks a field invalid with your own message. Passing an empty string clears it.
novalidate
A form attribute that turns off the browser's validation bubbles so you can show your own messages.
aria-describedby
Links a field to the element that describes it, such as an error message, so screen readers read it out.