How to handle form submission with JavaScript

· Category: JavaScript

Short answer

Listen for the submit event on the form, call event.preventDefault() to stop the default page reload, validate inputs, and submit data asynchronously with fetch.

Steps

  1. Intercept submission: javascript document.querySelector("#myForm").addEventListener("submit", async (e) => { e.preventDefault(); const formData = new FormData(e.target); const data = Object.fromEntries(formData); // validate data here const response = await fetch("/api/submit", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); if (!response.ok) throw new Error("Submit failed"); });
  2. Validate before sending: javascript if (!data.email.includes("@")) { showError("Invalid email"); return; }
  3. Provide user feedback on success or error.

Tips

  • Use the FormData API to collect fields without manual DOM queries.
  • Always validate on the server as well; client-side validation is for UX only.

Common issues

  • Forgetting preventDefault() causes a full page reload.
  • Named submit buttons may not be included in FormData if triggered programmatically.