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">

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

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

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

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

</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 object
*/

function clickHandler (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 object
*/

function submitHandler (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. 👍