Why does a form reload the page?
Forms are older than JavaScript: what the default submission really does, why preventDefault exists and why checking in the browser isn't protection.
Forms appeared in HTML before JavaScript — in the early '90s, when a page couldn't run any code at all. So how did you send an order or a search query? The browser did everything:
- it collected
name=valuepairs from the fields that have anameattribute; - it sent them to the address in the
actionattribute (by default, the same address) using themethodattribute (by defaultGET, which puts the data right into the address:?name=Whiskers&age=3); - it showed the server's response as a new page.
The "reload" is really a navigation to the response page. The old page, with all your code's variables, is simply gone.
const form = document.querySelector("form");
console.log(form.method);
console.log(new URLSearchParams(new FormData(form)).toString());+, and special characters get encoded.JavaScript arrived in 1995, and forms learned to fire a submit event before sending. Your handler runs first, then the browser performs its default action. event.preventDefault() says: "thanks, I'll take it from here". The submission is cancelled, the page stays, and your code can check the data, show errors and send the entry itself — with fetch, no reload. fetch is the next chapter.
So why not throw <form> away and put a click handler on an ordinary button? Because a form gives you a lot for free:
- Enter in a field submits the form, and a phone shows a "Go" key;
- password managers and autofill understand which field is the login and which is the address;
- screen readers announce the form and its fields;
- if JavaScript fails to load, a form with an
actionstill works.
That last point is called progressive enhancement: the basics work in plain HTML, and JavaScript makes them nicer — checking as you type and sending without a reload.
const form = document.querySelector("form");
const name = document.querySelector("#name");
console.log("Can the form be sent?", form.checkValidity());
name.removeAttribute("required"); // exactly what you can do in DevTools
console.log("And now?", form.checkValidity());Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.