DOM & Browser APIs

Forms

Forms are the primary way users submit data on the web. JavaScript unlocks real-time validation, dynamic fields, the powerful FormData API, and seamless AJAX submission — all without page reloads.

How do you handle a form with JavaScript?

Listen for the form's submit event, call event.preventDefault() to stop the page reload, and read all values at once with new FormData(form) (or Object.fromEntries(new FormData(form)) for a plain object). Validate, then send the data with fetch. Let HTML attributes like required and type="email" handle basic validation.

form.addEventListener("submit", async (e) => {
  e.preventDefault();
  if (!form.checkValidity()) return form.reportValidity();
  const data = Object.fromEntries(new FormData(form));
  const res = await fetch("/api/signup", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
});

ValidityState Properties

valueMissingrequired attribute set but field is empty
typeMismatchvalue doesn't match the input type (email, url…)
tooShort / tooLongoutside minlength / maxlength bounds
rangeUnderflow / rangeOverflowoutside min / max bounds
patternMismatchvalue doesn't match pattern attribute regex
customErrorsetCustomValidity() called with a message
validtrue only if ALL validity checks pass

FormData Cheatsheet

new FormData(form)Capture all named fields automatically
fd.get('email')Get value of a single field
fd.getAll('tags')Get all values for a multi-value field
fd.set('name', 'Alice')Override / set a value
fd.append('file', blob)Add a file/blob entry
Object.fromEntries(fd)Convert to plain object (one value per key)
new URLSearchParams(fd)Serialize to query string format
fetch(url, { body: fd })Send as multipart/form-data

Validation HTML Attributes

required<input required>
minlength<input minlength="3">
maxlength<input maxlength="50">
min / max<input type="number" min="1" max="100">
pattern<input pattern="[A-Za-z]+">
type=email<input type="email">
type=url<input type="url">
novalidate<form novalidate>

Common Pitfalls

Forgetting e.preventDefault() — form submits and page reloads, losing your SPA state
Always call e.preventDefault() in the submit handler when handling submission with JS
Reading e.target.value inside the submit event — works but fields are cleared after reset()
Read field values directly from input references or via FormData before calling form.reset()
Validating only on submit — frustrating UX, user must scroll back to find errors
Validate on blur and clear errors on input for immediate, friendly feedback
Object.fromEntries(fd) drops duplicate keys (checkboxes, multi-select)
Use fd.getAll('field') to retrieve all values for checkbox groups and multi-selects

Interactive Form Demo

Code Editor

<form id="signup" novalidate>
  <label>Name <input name="name" required></label>
  <label>Email <input name="email" type="email" required></label>
  <label><input type="checkbox" name="news"> Newsletter</label>
  <button>Sign up</button>
</form>
<pre id="out"></pre>

Preview

JavaScript Forms: summary

Key points

  • Inputs need a name attribute to appear in FormData.
  • Checkbox values are only present when checked.
  • Disable the submit button while sending to prevent double submissions.
  • Show errors next to the field and connect them with aria-describedby.

Frequently asked questions

›How do I get the value of an input?

input.value (always a string). Use input.valueAsNumber or Number(input.value) for numbers, and checkbox.checked for checkboxes.