Forms
Overview
Forms are how people give your page information. JavaScript can read the values, check them, and send them without reloading the page.
<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.
Handling submit
Listen for submit on the form — it also fires when someone presses Enter:
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
const email = form.elements.email.value;
const agreed = form.elements.terms.checked; // checkboxesform.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 + 1gives'21', not3. Convert withNumber()first.
Reading everything with FormData
new FormData(form) collects every named field in one go. Object.fromEntries turns it into a plain object:
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:
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
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:
const pw = form.elements.password;
pw.setCustomValidity(pw.value.length < 8 ? 'Use at least 8 characters.' : '');Built-in validation attributes
<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
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 fieldA 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:
input:user-invalid { border-color: #c0392b; }While sending
Give feedback and prevent double submissions:
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.
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.
const form = document.querySelector('form');const form = document.querySelector('form');
const nameField = form.elements.name;
form.addEventListener('submit', (event) => {
event.preventDefault();
nameField.setCustomValidity(
nameField.value.trim().length < 2 ? 'Please enter at least 2 characters.' : '',
);
if (!form.reportValidity()) return;
const data = Object.fromEntries(new FormData(form));
console.log(data); // { name: '…', email: '…' }
});Summary
- Listen for
submiton the form, notclickon the button. new FormData(form)reads every named field at once;Object.fromEntriesturns it into an object.- Field values are always strings — convert numbers yourself.
- Use HTML validation (
required,type="email") first, then add your own checks withsetCustomValidity. - Disable the button while sending, show the result, and always validate on the server too.