Forms and JavaScript: Intercepting a form submit event using JavaScript

We’ve seen what’s the default behavior of forms, without JavaScript.

When we hit “enter” in a form that has an input field, the form is submitted to the current route using the HTTP method specified, by default GET, sending the data.

Using JavaScript we can intercept the submit event on the form element (not an input field, the form itself):

const form = document.querySelector('form')
form.addEventListener('submit', event => {
  // submit event detected
})

Now inside the submit event handler function we call the event.preventDefault() method to prevent the default browser behavior:

const form = document.querySelector('form')
form.addEventListener('submit', event => {
  // submit event detected
  event.preventDefault()
  alert('form submit event!')
})

In this way we can avoid a form submission to reload the page, and we can do whatever we want now with JavaScript.

Note that unless you use a framework that takes care of this for you, you’ll also need to wrap that in the DOMContentLoaded event callback, so your event handler is attached to the DOM element after the DOM has been loaded (otherwise it might be attached before, end it ends up failing to work):

document.addEventListener('DOMContentLoaded', () => {
  const form = document.querySelector('form')
  form.addEventListener('submit', event => {
    // submit event detected
    event.preventDefault()
    alert('form submit event!')
  })
})

Full example in a plain HTML file:

<html>
  <head>
    <script>
      document.addEventListener('DOMContentLoaded', () => {
        const form = document.querySelector('form')
        form.addEventListener('submit', event => {
          // submit event detected
          event.preventDefault()
          alert('form submit event!')
        })
      })
    </script>
  </head>

  <body>
    <form method="post">
      <input type="text" name="city" />
    </form>
  </body>

</html>

At this point submitting the form will not do anything apparently, except give us control. But we can do anything we want, now. Typically this means validating the inputs and sending data to a server using the Fetch API.

Lessons in this unit:

0: Introduction
1: Inspect the value of an item
2: Listen to events on input fields
3: ▶︎ Intercepting a form submit event using JavaScript
Want to learn more? Check out our courses