Forms

Topic 5 of 5 in Working with the DOM6 min readBeginnerFree course

Overview

Forms are how people give your page information. JavaScript can read the values, check them, and send them without reloading the page.

HTML
<form id="signup">
  <label>Name <input name="name" required></label>
  <label>Email <input name="email" type="email" required></label>
  <button>Sign up</button>
</form>

Start with good HTML: every field has a name (that’s how its value is identified) and a <label> (so people — and screen readers — know what it’s for). A <button> inside a form submits it by default.

Six steps: the form is submitted by Enter or the button; preventDefault() stops the page reloading; validate with built-in and custom rules; new FormData reads every field; fetch sends it to the server; show the result. If invalid, show messages next to the fields and stop.

Handling submit

Listen for submit on the form — it also fires when someone presses Enter:

JavaScript
const form = document.querySelector('#signup');

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const data = Object.fromEntries(new FormData(form));
  await fetch('/api/signup', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
});

Listening for click on the button instead misses Enter-key submissions and skips the browser’s built-in validation.

Reading single fields

JavaScript
const email = form.elements.email.value;
const agreed = form.elements.terms.checked; // checkboxes

form.elements gives you every field by its name. Some details by field type:

Field Read with Notes
text, email, textarea .value always a string
number, range .value or .valueAsNumber .value is still a string!
checkbox .checked true / false
radio group form.elements.size.value the chosen option’s value
select .value the selected option’s value
date .value or .valueAsDate .value is '2026-12-03'
file .files a list of File objects

Values are strings. form.elements.qty.value + 1 gives '21', not 3. Convert with Number() first.

Reading everything with FormData

new FormData(form) collects every named field in one go. Object.fromEntries turns it into a plain object:

JavaScript
const data = Object.fromEntries(new FormData(form));
// { name: 'Asha', email: 'asha@example.com', plan: 'pro' }

Unticked checkboxes aren’t included at all, and fields that share a name (several checkboxes called topics) need getAll:

JavaScript
const fd = new FormData(form);
fd.getAll('topics'); // ['loops', 'arrays']

To upload files, send the FormData itself as the fetch body instead of JSON.

Reacting while typing

JavaScript
form.elements.name.addEventListener('input', (e) => {
  preview.textContent = e.target.value;
});

input fires on every keystroke; change fires when the field loses focus. Use input for live previews, character counters and search-as-you-type; use change for things that should happen once the person has finished.

Validation

Attributes like required, type="email", min and pattern give you free checks and error messages. Add custom rules with setCustomValidity:

JavaScript
const pw = form.elements.password;
pw.setCustomValidity(pw.value.length < 8 ? 'Use at least 8 characters.' : '');

Built-in validation attributes

HTML
<input name="name" required minlength="2" maxlength="50">
<input name="email" type="email" required>
<input name="age" type="number" min="13" max="120">
<input name="pin" pattern="\d{6}" title="Six digits">
<input name="site" type="url">

The browser checks these on submit, blocks submission if anything’s wrong, focuses the first problem field and shows a message — no JavaScript needed.

Checking from JavaScript

JavaScript
input.checkValidity();   // true / false, silently
form.reportValidity();   // checks every field and shows messages
input.validity.valueMissing; // details: tooShort, typeMismatch, patternMismatch…
input.validationMessage; // the browser's message for this field

A message set with setCustomValidity stays until you set it back to '' — so update it on every input event, or right before you check.

Styling valid and invalid fields

CSS can style fields by their state. :user-invalid only applies after someone has interacted with the field, so people aren’t greeted with red boxes:

CSS
input:user-invalid { border-color: #c0392b; }

While sending

Give feedback and prevent double submissions:

JavaScript
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const button = form.querySelector('button');
  button.disabled = true;
  button.textContent = 'Sending…';
  try {
    const res = await fetch('/api/signup', { method: 'POST', body: new FormData(form) });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    form.reset();
    status.textContent = 'Thanks — check your inbox!';
  } catch {
    status.textContent = 'Something went wrong. Please try again.';
  } finally {
    button.disabled = false;
    button.textContent = 'Sign up';
  }
});

form.reset() puts every field back to its starting value.

Always validate on the server too. Anything in the browser can be bypassed. Browser validation is for convenience — quick, friendly feedback. The server is where rules are actually enforced.

Exercise

Read a sign-up form

On submit, stop the page reloading and log an object with the form’s name and email values. If the name is shorter than 2 characters, show the browser’s validation message instead of logging.

JavaScript
const form = document.querySelector('form');

Summary

  • Listen for submit on the form, not click on the button.
  • new FormData(form) reads every named field at once; Object.fromEntries turns it into an object.
  • Field values are always strings — convert numbers yourself.
  • Use HTML validation (required, type="email") first, then add your own checks with setCustomValidity.
  • Disable the button while sending, show the result, and always validate on the server too.