Lesson 12 of 28
In progress
Forms: reading values and showing errors
Handle submit, read fields with FormData, validate before sending, and put error messages where people can find them.
A form is the main way a page receives structured input. Handling it well means stopping the reload, reading values deliberately, validating in a way people can act on, and never losing what they typed.
What you will learn
- Handle submit and read values with
FormData. - Validate with clear, announced messages.
- Keep the form usable while a request runs.
Listen for submit, not click
Editable. Runs in your browser.
<script>
const form = document.querySelector("#signup");
const status = document.querySelector("#status");
form.addEventListener("submit", (event) => {
event.preventDefault();
status.textContent = "Submitting " + form.email.value;
});
</script>
Press Run to see the output.
The event fires for a click and for Enter in a field, which is why it is the right hook. preventDefault stops the browser’s navigation so the page does not reload.
Named controls become properties on the form: form.email. That is convenient and fragile if a field name collides with a form property such as submit or action. FormData avoids the collision.
FormData
Editable. Runs in your browser.
<script>
document.querySelector("#profile").addEventListener("submit", (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(event.target));
console.log(data);
});
</script>
Press Run to see the output.
FormData collects every named control, including checkboxes and selects. Object.fromEntries turns it into a plain object for logging or JSON. File inputs need the FormData object itself, not a converted copy.
Checkboxes that are unchecked are absent from the data, which is correct: "not selected" is the absence of a value.
Checkboxes, radios and files
A checkbox group needs a different read than a text field. FormData gives you one entry per checked box under the same name, and a radio group gives exactly one value.
Editable. Runs in your browser.
const data = new FormData(form);
console.log(data.getAll("topics"));
console.log(data.get("level"));
Press Run to see the output.
getAll returns every checked value for a name, while get returns the first. For a single checkbox, test data.has("name") rather than comparing to "on", which is the default value when you omit one.
File inputs expose a files FileList. Check files.length before reading, and never trust the file type reported by the browser; the server must validate content anyway.
Validation with a place to look
The browser’s built-in validation is a useful first pass. For anything more specific, render your own message next to the field and connect it with aria-describedby.
Editable. Runs in your browser.
<script>
const form = document.querySelector("#booking");
const seats = form.querySelector("#seats");
const error = form.querySelector("#seats-error");
form.addEventListener("submit", (event) => {
event.preventDefault();
const value = Number(seats.value);
if (!Number.isInteger(value) || value < 1 || value > 6) {
error.textContent = "Choose between 1 and 6 seats.";
seats.setAttribute("aria-invalid", "true");
seats.focus();
return;
}
error.textContent = "";
seats.removeAttribute("aria-invalid");
console.log("Booked", value);
});
</script>
Press Run to see the output.
novalidate turns off the browser bubbles so your message is the only one shown. Moving focus to the invalid field means a keyboard user does not have to hunt for the problem. Clearing the message on success matters as much as showing it on failure.
Do not disable the submit button to prevent invalid input. A disabled button cannot be focused, so the reason for it is invisible to a keyboard user. Validate on submit instead.
While a request runs
If submission sends data somewhere, show that it is working and prevent a double submit.
async function save(form, button) {
button.disabled = true;
button.textContent = "Saving...";
try {
await new Promise((resolve) => setTimeout(resolve, 800));
return true;
} finally {
button.disabled = false;
button.textContent = "Save";
}
}
The finally restores the button even when the request fails. Disabling during the request is fine because it is brief and explained by the label; disabling before the form is valid is not.
Reset and preserved input
form.reset() restores the initial values. Use it after a successful submission, not after a failed one: losing typed input because of a server error is infuriating.
If you re-render the form’s HTML after an error, the values disappear. Update the error text in place instead, and keep the fields untouched.
Reading event.target.value in a submit handler gives the value of the form, not the field, because the target is the form. Read fields through FormData or form.elements.namedItem("email").value.
Build a form with a name and an email. On submit, validate that the name is at least two characters and the email contains an @. Show one message per field, focus the first invalid field, and log the collected object on success.
Show solution
Editable. Runs in your browser.
<label for="e">Email</label>
<input id="e" name="email" aria-describedby="e-err">
<p id="e-err" role="alert"></p>
<button type="submit">Send</button>
</form>
<script>
const form = document.querySelector("#demo");
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(form));
let firstBad = null;
const nameError = data.name.trim().length < 2 ? "Enter at least two characters." : "";
const emailError = data.email.includes("@") ? "" : "Enter an email address with @.";
form.querySelector("#n-err").textContent = nameError;
form.querySelector("#e-err").textContent = emailError;
if (nameError) firstBad = form.querySelector("#n");
else if (emailError) firstBad = form.querySelector("#e");
if (firstBad) {
firstBad.setAttribute("aria-invalid", "true");
firstBad.focus();
return;
}
console.log(data);
});
</script>
Press Run to see the output.
Both messages are updated on every submit so a fixed field clears its error. Focus goes to the first problem, which is the order a person reads the form.
Recap
- Handle
submitand callpreventDefault; read values withFormData. - Show specific messages, connect them with
aria-describedby, and focus the first invalid field. - Disable only during a real request, and restore state in
finally.
Next, you will put selection, updates and events together in a small interactive panel.
Should I validate on every keystroke?
How do I send form data with fetch?
Progress is saved in this browser only. No account, no email.