CodeBlanks Logo Icon CodeBlanks

The form submit event

JavaScript course · Intermediate · Lesson 56/134

Learn to capture the submit event and prevent page reload with preventDefault.

The submit event

When a form is sent, the submit event fires. To catch it, you pass the 'submit' type to the addEventListener method.

const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
  console.log('Submitted');
});

You add the listener to the form, not to the button. A form can be sent with Enter or with a submit button; in both cases the submit event fires.

Stopping reload with preventDefault

By default, the submit event reloads the page. To stop this, you call the preventDefault method on the event object.

form.addEventListener('submit', (event) => {
  event.preventDefault();
  console.log('No reload');
});

It is safest to put this line at the top. This way you can work with the form data in JavaScript and show the result without reloading the page.

Exercise Add a submit listener

The form variable points to a <form> element. Listen for the submit event, call event.preventDefault() to stop the page reload, and log 'Submitted' to the console.

Show example solution
form.addEventListener('submit', (event) => {
  event.preventDefault();
  console.log('Submitted');
});

Test yourself

  1. Which catches the form submit?

    const form = document.querySelector('form');
    // A
    form.addEventListener('click', () => {});
    // B
    form.addEventListener('submit', () => {});
    // C
    form.addEventListener('send', () => {});
    // D
    form.addEventListener('change', () => {});
    • A
    • B
    • C
    • D
    Show answer

    B — Correct! The submit event fires only when the form is sent.

  2. Match terms to their meanings

    submit
    Form send event
    preventDefault()
    Stops page reload
    event
    The event object
  3. Complete the preventDefault call

    form.addEventListener('submit', (event) => {
      event.____();
    });
    Show answer
    form.addEventListener('submit', (event) => {
      event.preventDefault();
    });

All lessons in Intermediate