Invio modulo + preventDefault: interrompe il ricaricamento della pagina
The default form-submit behaviour
When you click a submit button or press Enter in an input, the browser:
- Builds a form payload (every named input's
value). - Navigates the browser to the URL in
action=, replacing the page.
In modern SPAs you almost always want to handle the submit in JavaScript instead — keep the page alive, send the data via fetch, update part of the UI.
The intercept
form.addEventListener("submit", (event) => {
event.preventDefault();
// your code: build payload, call fetch, update UI
});preventDefault() cancels the navigation. The form stays put. You're now in charge.
Read all fields cleanly: FormData
const data = new FormData(form);
data.get("email"); // single value
[...data.entries()]; // array of [name, value] pairs
const obj = Object.fromEntries(data);FormData understands files, multi-value selects, checkboxes — all the edge cases hand-coded readers miss. It's the standard browser way to read a form.
Don't break native validation by accident
event.preventDefault() cancels submission. If you call it BEFORE checking form.checkValidity(), you've also bypassed the browser's built-in required/pattern checks. Either let the browser validate first, or rebuild the same checks in your handler.
Iscriviti per iniziare a programmare
La teoria è aperta a tutti. Editor, anteprima e check si sbloccano con una prova gratuita di 7 giorni — carta richiesta, annullabile in qualsiasi momento.
Iscriviti — prova gratuita →Le prime 10 lezioni di ogni percorso sono gratuite. Nessuna carta richiesta.