JavaScript handles form interactions by listening for the submit event, stopping the default browser page reload with event.preventDefault(), and reading input values cleanly via FormData or direct element references.
FormDataInstead of querying ten separate input elements one by one, pass event.target (the <form>) into new FormData(form) to collect every named field automatically. Converting it via Object.fromEntries(formData) produces a ready-to-send payload object.
Browser HTML5 attributes (required, type="email", minlength="8") pair cleanly with JavaScript's Constraint Validation API (input.checkValidity() and input.setCustomValidity()). Remember that client-side validation improves UX only—your backend API must always validate inputs again.
const app = document.getElementById("app");
if (app) {
app.innerHTML = `
<form id="contact-form">
<input name="email" type="email" value="[email protected]" required />
<input name="age" type="number" value="22" min="13" required />
<button type="submit">Join</button>
</form>
`;
const form = document.getElementById("contact-form");
const data = Object.fromEntries(new FormData(form));
const isValid = form.checkValidity();
console.log("Form valid:", isValid);
console.log("FormData payload:", data);
}
click instead of form submit: Users often submit forms by pressing Enter inside a text input; attaching your handler to form.addEventListener("submit", ...) catches both button clicks and Enter presses.name attributes on inputs when using FormData: FormData skips any <input> or <select> that lacks a name="..." attribute.checkbox.value: A checkbox's .value defaults to "on" even when unchecked! Always read checkbox.checked (a boolean).event.preventDefault() do on a form submit event?It stops the browser from performing a traditional page-reloading HTTP submission, letting your JavaScript send a fetch() JSON request and update the page smoothly.
FormData?Call formData.getAll("fieldName"), which returns an array of every selected value for that field name.
Call formElement.reset(), which restores every input back to its initial HTML default value.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.