DEV Community

Cover image for Listening for a Form Submit in JavaScript
Nick
Nick

Posted on

Listening for a Form Submit in JavaScript

What is a Form Submit?

Simply put it's submitting a form... Basically, when you fill the form out with whatever information it asks for you want to do something with that information. We can do all manner of operations with this data and that's dependent upon your application's tasks and the purpose of the form.

A contact form should provide ways to get in touch with a specific person; a suggestion form should include an issue or improvement to be logged; an email subscription sign-up should have... well, an email. You get the point.

How do we listen for the submission?

First, we're grabbing the element (the form in this case) that we want to listen to. Keep in mind, this is using the basic form element selector. If you have multiple forms on your page this will only return the first occurrence of a form.

If you do have multiple forms, you'll want to add an id tag to each form specifying what it's for - that way you can safely select the form you want and attach the appropriate event listener.

  const form = document.querySelector('form')
  form.addEventListener('submit', (event) => {
    // Add code for functionality you need here
  })
Enter fullscreen mode Exit fullscreen mode

Or you can simply chain the method calls like so...

  document.querySelector('form').addEventListener('submit', (event) => {
    // Add code for functionality you need here
  })
Enter fullscreen mode Exit fullscreen mode

This chaining is especially useful when you know you'll only have one event to listen for. No need to grab the element in question and store it in a variable if you're only going to add one event listener.

Why are we not listening to the submit button?

For us to have access to the information the user has entered we listen form. The button will not actually be targeted by a submit event. The button is the submitter.

This is apparent when you look in the SubmitEvent object that is generated when a form is submitted; there is a submitter property in which you'll see the element triggering the submission. So we listen for submission on the form and the button is the one that triggers that event.

Our submit button plays a pivotal role to get this all to work, however, our form is the element on which the submit is actually fired and thus the element we should listen to.

Top comments (0)