How can I listen to the form submit event in javascript?
Attach an event listener with addEventListener
to the form's 'submit'
event. Prevent form from relaunching the page with event.preventDefault()
, this way you're at liberty to execute your code such as validation or sending a request smoothly.
Here, the form is directly targeted with querySelector()
and event.preventDefault()
assures control over the submission process.
The next level: event handling and form validation
Multi-Browser Event Attachment
In case of multiple browser support, check if addEventListener
is available, if not switch to attachEvent
:
Using HTML5 Validation as Guardian Angel
HTML5 form validation acts like a built-in validator for the forms before submission. However, for browsers that still live in the stone age, a trusty JavaScript fallback can come in handy:
Handling Multiple Forms and Libraries
Regardless of the number of forms you have, with pure JavaScript, you can attach submit listeners to them without relying on inline handlers:
For an even more standalone library:
Nailing framework-dependent form handling
AngularJS form submission
In AngularJS, ensure the form submission is intently listening within the directive:
Tackling React form handling
With React, leverage the onSubmit
props to your advantage:
Flexibility and User-friendly Approach
Keep in mind your forms are built for users. So maintain a user-friendly approach that feeds back on validation failures with maybe a customized message near the faulty field. Design a validation library that can be easily incorporated into various templates and front-end frameworks.
Was this article helpful?