How to detect form submissions in JavaScript

There’s a right way and a wrong way to detect form submissions in JavaScript. I want to help you do it the right way 😊

Let’s assume the following HTML for a simple contact form:

<form action="contact.php" method="post">

  <div>
    <label for="name">Name</label>
    <input id="name" type="text" name="name">
  </div>

  <div>
    <label for="email">Email</label>
    <input id="email" type="email" name="email">
  </div>

  <div>
    <label for="message">Message</label>
    <textarea id="message" name="message"></textarea>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>

</form>

The wrong way

I sometimes see people attach a click handler to the submit button, like so:

// Get the submit button
var submitButton = document.querySelector("[type='submit']");

/**
 * Handle click events
 * @param {Object} event The Event interface
 */
var clickHandler = function (event) {
  // Do something on click...
};

// Attach the click handler to the submit button
submitButton.addEventListener("click", clickHandler);

The thing is, this only applies to click events on the button itself. Users should always be able to submit forms by pressing the Enter key while one of the inputs is in focus. This approach won’t work.

The right way

We don’t care if the user clicked the submit button. We actually want to know if they submitted the form. These are two different things.

Instead, you should listen to the submit event on the form itself:

// Get the form
var form = document.querySelector("form");

/**
 * Handle submit events
 * @param {Object} event The Event interface
 */
var submitHandler = function (event) {
  // Do something on submit...
};

// Attach the submit handler to the form
form.addEventListener("submit", submitHandler);

Now the user can submit the form by either clicking the submit button or pressing the Enter key 👍


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!