Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 156 ยท The DOM

Working with Forms

Handle forms in JavaScript - read fields with form.elements, collect values with FormData, use the constraint validation API and handle submit events properly.

Forms are where users talk back to your page: sign-ups, searches, checkouts, settings. HTML already does a lot on its own โ€” fields, labels, built-in validation, submission. JavaScript steps in when you want more: live feedback while typing, custom validation rules, sending data without reloading the page, or turning the answers into a JavaScript object.

You built forms in HTML in the Forms chapter and met built-in checks in Form Validation. This lesson is the JavaScript side. You will read each type of field correctly, collect everything at once with FormData, drive the browser's constraint validation API, and write a submit handler that behaves well.

No real servers here. The examples in this lesson never send data anywhere. Each submit handler calls preventDefault() and prints the collected data instead, which is also exactly where your own code would hand the data to fetch().

Finding the form and its fields

Give fields a name attribute โ€” you need it for submission anyway โ€” and you can reach them through the form's elements collection:

JavaScript
const form = document.querySelector("#signup");
form.elements.email;          // the field with name="email"
form.elements["first-name"];  // bracket notation for names with dashes
form.elements.length;         // number of controls (fields, buttons, fieldsets)

Every field also points back at its form with field.form, which is handy inside event listeners.

When several fields share a name, as radio buttons do, form.elements.size returns a RadioNodeList. Its value property is the value of the checked radio (or an empty string when none is checked), which saves you a loop.

Reading each kind of field

The value property is always a string, even for type="number". Each kind of field has its own details:

Field Read with Notes
Text, email, textarea field.value A string; often worth .trim().
Number, range field.valueAsNumber A number, or NaN when empty.
Date field.value / field.valueAsDate "2026-10-14", or a Date in UTC.
Checkbox field.checked value is the text sent if checked (default "on").
Radio group form.elements.name.value Value of the checked radio.
Select select.value Value of the selected <option>.
Multi-select select.selectedOptions A collection of the chosen options.
File field.files A FileList of File objects.
Reading every kind of field

Change some answers and read them again. Notice the RadioNodeList for the room, and how selectedOptions turns a multi-select into a clean array.

input and change

Two events cover nearly all live behavior:

  • input fires on every change to the value: each keystroke, each slider step, each paste.
  • change fires when a change is committed: when a text field loses focus after editing, or immediately for checkboxes, radios, selects and date pickers.

Use input for instant feedback such as character counters and live previews, and change for actions that should happen once per decision. Both bubble, so a single listener on the <form> can handle every field, as you saw in Bubbling, Capturing and Delegation.

The submit event

Always handle the submit event on the form, not click on the button. Submission can happen in several ways โ€” clicking a submit button, pressing Enter in a text field, a script calling requestSubmit() โ€” and submit catches all of them.

In the handler:

  • event.preventDefault() stops the browser's own submission and page navigation, so your code can take over.
  • event.submitter is the button that triggered the submission (or null when there wasn't one). This lets a form have several submit buttons, such as "Save draft" and "Publish".

Importantly, submit only fires once the browser's built-in validation has passed. If a required field is empty, the browser shows its message and your handler never runs, unless the form has the novalidate attribute.

To submit a form from code, call form.requestSubmit(). It runs validation and fires the submit event, exactly like a click. The older form.submit() skips both and sends the form immediately, which is rarely what you want.

Collecting everything with FormData

new FormData(form) gathers every successful field of a form into one object: name-value pairs, exactly as the browser would send them. Disabled fields, unchecked checkboxes and fields without a name are left out.

  • data.get("name") โ€” the first value for a name, or null.
  • data.getAll("name") โ€” every value for a name, as an array (checkbox groups, multi-selects).
  • data.has("name"), data.set(name, value), data.append(name, value), data.delete(name).
  • It is iterable: for (const [name, value] of data).

To turn it into a plain object, use Object.fromEntries(data). Be careful: when a name appears several times, only the last value survives, so read those with getAll().

Submit handling with FormData

Try submitting with an empty email: the browser blocks it before your handler runs. Then fill it in and use both buttons; the intent field tells you which one was pressed. Passing the submitter as the second argument to FormData is supported in all current browsers; in older ones, read event.submitter.value directly as the code also does.

When you do talk to a server, you can pass the FormData object straight to fetch() as the body, or convert it with new URLSearchParams(data) for a URL-encoded body or JSON.stringify(payload) for JSON.

The constraint validation API

HTML validation attributes โ€” required, type="email", min, max, minlength, pattern โ€” are backed by a JavaScript API on every field:

  • field.validity โ€” a ValidityState object with boolean flags such as valueMissing, typeMismatch, tooShort, rangeUnderflow, patternMismatch, customError and the overall valid.
  • field.validationMessage โ€” the browser's message for the current problem, in the user's language.
  • field.checkValidity() โ€” returns true or false, and fires an invalid event on failure.
  • field.reportValidity() โ€” the same, but also shows the message bubble to the user.
  • field.setCustomValidity(message) โ€” marks the field invalid with your own message. Pass an empty string "" to make it valid again; forgetting this leaves the field permanently invalid.

The same checkValidity() and reportValidity() exist on the form, checking every field.

Custom rules usually go in an input listener: compute whether the value is acceptable, then call setCustomValidity() with a message or with "". Pair it with the CSS :user-invalid pseudo-class, which matches invalid fields only after the user has interacted with them, so you don't shout at people before they type. It is supported in all major browsers since 2023; :invalid is the older fallback that matches immediately.

Custom validation rules

Type ad, then admin, then Ad min and watch the messages change: too short, taken, wrong pattern. Each message comes from validationMessage, so built-in and custom errors show up the same way. The submit handler only runs once every field is valid.

If you want to show all messages in your own UI instead of the browser bubbles, add novalidate to the form and call form.checkValidity() yourself at the start of the submit handler.

Good submit-handler habits

  • Prevent double submits. Disable the submit button (button.disabled = true) while work is in progress, and re-enable it afterwards in a finally block.
  • Keep focus useful. After an error, move focus to the first invalid field with form.querySelector(":invalid")?.focus().
  • Reset deliberately. form.reset() restores every field to its default value (the HTML attributes), and fires a reset event you can listen for.
  • Validate on the server too. Anyone can bypass browser checks. Client-side validation is for a pleasant experience; the server must still check everything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does form.elements.quantity.value return for <input name="quantity" type="number"> containing 4?

    value is always a string. Use valueAsNumber or Number() to get a number.
  2. 2. Why listen for submit on the form instead of click on the submit button?

    submit fires however the form is submitted, and only after built-in validation passes.
  3. 3. A form has three checkboxes named topic, two of them checked. What does Object.fromEntries(new FormData(form)).topic contain?

    Object.fromEntries() keeps the last value for a repeated name. Use data.getAll("topic") to get them all.
  4. 4. After field.setCustomValidity("Too expensive"), the user fixes the value. What must your code do?

    A custom error stays until you clear it with an empty string, so recompute it in an input listener.
  5. 5. What is the difference between form.requestSubmit() and form.submit()?

    requestSubmit() behaves like clicking a submit button. submit() sends the form immediately without validation or a submit event.

Summary

  • Reach fields by name with form.elements; radio groups come back as a RadioNodeList with a handy value.
  • value is always a string; use valueAsNumber, checked, selectedOptions and files for the right type.
  • Use input for live feedback and change for committed changes; both bubble to the form.
  • Handle submit on the form, call preventDefault(), and use event.submitter to know which button was used; requestSubmit() submits from code.
  • new FormData(form) collects every successful field; use getAll() for repeated names and Object.fromEntries() for a plain object.
  • The constraint validation API (validity, validationMessage, checkValidity(), reportValidity(), setCustomValidity()) plus :user-invalid gives friendly, consistent validation. Always validate on the server as well.

Next: Traversing the DOM โ€” moving between parents, children and siblings, and walking whole trees.