How to track form submission in JavaScript
Why track form submission
If you're using a client-side MVC framework like Angular, Ember or Backbone or if you're looking to trigger some custom events when a user submits a form like a loading indicator or a confirmation message, you're going to want to listen for that form submission with a script.
How to do it
Listen for submit event on the form element
<script>
function submitHandler() {
// do something...
}
</script>
<form onsubmit="submitHandler();">
// if you're using Angular, use the `ng-submit` directive
// inputs and such...
<button type="submit">Submit</button>
</form>
For form submission, make sure to listen on the form element and not on the submit button. If you only listen for clicks on the submit button, the form won't submit when someone hits Enter
. It also limits support for some browsers like screen readers. If you want to attach events to the submit button, consider adding an analytics click tracker. Then you can see exactly how many of your users are actually using the button to submit.
Use flexible, semantic markup whenever you can
Notice that the example code above makes use of a button
tag and not an input
. As long as you add the type="submit"
attribute, these will submit the form exactly the same way. The difference is that button
s can contain arbitrary HTML and input
s cannot. It's generally a good practice to use button
s to submit forms all the time to give yourself more flexibility in styling them.
This difference is related to another best-practices discussion around when to use a button
and when to use an a
tag. Anchor tags should generally only be used when a user can click an element to navigate to another URL whether that be on your site or elsewhere. They can also be used with plain hashes to navigate to sections of a page. button
s on the other hand should be used when what the user clicks on performs an action but does not necessarily change the URL. This element should be used for things like form submission, hiding and showing elements on the page, loading data over ajax and changing sub-states in single page applications. Knowing and exploiting the subtle difference between these two elements allows developers to write less code and code that's easier to understand.