Code Literacy

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

What worksJavaScript
form.addEventListener('submit', (event) => {
  event.preventDefault();
  if (!email.value.includes('@')) {
    error.textContent = 'Please enter a valid email.';
    return;
  }
  thanks.hidden = false;
});
No reload; checks run for clicks and Enter alike.

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.

40 minutes See it Build it Say it
Start the lesson

Free with an account. The first two units need no account.

© 2026 webfaCeMEdia. Code Literacy™ is a trademark of webfaCeMEdia.