Handling Forms
Forms are how users send you information: sign-ups, searches, payments, orders. With JavaScript you can read what they typed, check it before anything is sent, show helpful error messages and update the page without a reload. The key is listening for the form's submit event and calling preventDefault().
A form to work with
Every field that you want to read needs a name attribute. Wrap inputs in (or link them to) a <label> so the form is accessible.
<form id="signup">
<label>Full name <input name="fullName"></label>
<label>Phone <input name="phone"></label>
<label>County
<select name="county">
<option value="">Choose...</option>
<option>Nairobi</option>
<option>Kisumu</option>
</select>
</label>
<label><input type="checkbox" name="agree"> I agree to the rules</label>
<button>Join</button>
</form>
A <button> inside a form is a submit button by default. Use type="button" for buttons that should not submit.
The submit event and preventDefault
By default, submitting a form makes the browser send the data to the URL in the form's action and load a new page (or reload the current one). For a JavaScript-powered form you want to stay on the page, so you cancel that default behaviour:
const form = document.querySelector("#signup");
form.addEventListener("submit", (event) => {
event.preventDefault(); // stop the page from reloading
console.log("Form submitted, no reload");
});
Listen on the form, not the button. The submit event fires whether the user clicks the button or presses Enter in a text field, so one listener covers both.
preventDefault() (dashed path) the browser reloads the page before your code can show anything.Reading values
One field at a time
Every input has a value property. It is always a string, even for type="number", so convert it before doing maths. Checkboxes use checked (true or false).
const qty = document.querySelector("#qty"); // the user typed 3
console.log(qty.value, typeof qty.value);
console.log(qty.value + 2); // string joining!
console.log(Number(qty.value) + 2);
All fields at once with FormData
new FormData(form) collects every named field in one go. Use data.get(name) for a single value, or Object.fromEntries(data) to turn the whole form into a plain object.
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(form);
console.log(data.get("county"));
console.log(Object.fromEntries(data));
});
If Amina fills in her details and ticks the box, the console shows:
A ticked checkbox without a value attribute sends 'on'; an unticked one is left out completely, so test for it with data.has("agree").
Validating input
HTML can do basic checks for you. Attributes such as required, type="email", minlength="2" and pattern make the browser block submission and show its own message, and the :invalid CSS pseudo-class lets you style bad fields. For custom rules and your own messages, validate in JavaScript and add novalidate to the form so the browser's pop-ups don't get in the way.
function validate(data) {
const errors = [];
if (data.get("fullName").trim().length < 2) {
errors.push("Enter your name.");
}
if (!/^0[17]\d{8}$/.test(data.get("phone").trim())) {
errors.push("Phone must be 10 digits starting 07 or 01.");
}
if (!data.has("agree")) {
errors.push("Tick the box to agree.");
}
return errors;
}
Always trim() text first, so a name made only of spaces doesn't pass. The regular expression checks a Kenyan-style mobile number: a 0, then 1 or 7, then exactly eight more digits.
Forgetting the name attribute. FormData silently skips any field without one, so data.get("phone") returns null and .trim() then throws a TypeError. If a value is mysteriously missing, check the HTML first.
Browser checks are for the user's convenience only. Anyone can bypass them, so a real app must validate again on the server before trusting the data.
Try it: a club sign-up form
Submit the form empty to see the errors, then fill it in correctly. Try adding an email field with your own check.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
label { display: block; margin-top: 8px; }
button { margin-top: 10px; }
.error { color: #b3261e; }
</style>
</head>
<body>
<form id="signup" novalidate>
<label>Full name <input name="fullName"></label>
<label>Phone <input name="phone" placeholder="0712345678"></label>
<label>County
<select name="county">
<option value="">Choose...</option>
<option>Nairobi</option>
<option>Kisumu</option>
<option>Mombasa</option>
</select>
</label>
<label><input type="checkbox" name="agree"> I agree to the club rules</label>
<button>Join</button>
</form>
<p id="message"></p>
<ul id="members"></ul>
<script>
const form = document.querySelector("#signup");
const message = document.querySelector("#message");
const members = document.querySelector("#members");
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(form);
const fullName = data.get("fullName").trim();
const phone = data.get("phone").trim();
const county = data.get("county");
const errors = [];
if (fullName.length < 2) errors.push("Enter your name.");
if (!/^0[17]\d{8}$/.test(phone)) errors.push("Phone must be 10 digits starting 07 or 01.");
if (!county) errors.push("Choose a county.");
if (!data.has("agree")) errors.push("Tick the box to agree.");
if (errors.length > 0) {
message.className = "error";
message.textContent = errors.join(" ");
return;
}
const li = document.createElement("li");
li.textContent = `${fullName} (${county})`;
members.append(li);
message.className = "";
message.textContent = `Welcome, ${fullName}!`;
form.reset();
});
</script>
</body>
</html>
Key points
- Listen for
submiton the form and callevent.preventDefault()to stop the reload. input.valueis always a string; convert withNumber()before doing maths.new FormData(form)reads every field that has aname;Object.fromEntries()turns it into an object.- Trim and validate input, show clear messages, and remember the server must validate too.
Tip: use the ← and → keys to move between pages.
