Capstone · Build and ship something for a real person
Form submit: why the page reloads
By default a form sends itself and reloads the page, so anything your script showed is wiped. Listen for submit on the form and call event.preventDefault() first in the handler.
The mix-up
What people often think
“The form will just send itself without the page changing.”
What the tutor says
A form reloads the page by default, wiping your thank-you. Call event.preventDefault() first in the handler.
How it works
Listen on the form, not the button’s click. submit fires for a click and for pressing Enter in a field, so nobody slips past your checks.
preventDefault only stops the reload. It does nothing about what the visitor typed, so it is not a security feature: you still check the input, and the server checks it again.
An example
form.addEventListener('submit', (event) => {
event.preventDefault();
if (!email.value.includes('@')) {
error.textContent = 'Please enter a valid email.';
return;
}
thanks.hidden = false;
});Close cousins of this mix-up
The tutor watches for these in the same lesson.
“A form is submitted by a click on the button.”
Listen for submit on the form. It fires for a click and for pressing Enter, so nobody slips past your checks.
“preventDefault is a security feature that blocks attacks.”
preventDefault only stops the browser reloading the page on submit. It does nothing about what the visitor typed.
Practise it with a tutor watching
Make it do something
Write JavaScript that checks the form and shows a thank-you without reloading the page.
Free with an account. The first two units need no account.