Explain Codes LogoExplain Codes Logo

How can I listen to the form submit event in javascript?

javascript
event-handling
form-validation
javascript-libraries
Nikita BarsukovbyNikita Barsukov·Feb 10, 2025
TLDR

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.

document.querySelector('form').addEventListener('submit', function(event) { event.preventDefault(); // Stoppage of page refresh // Begin custom form data handling... console.log('Form submitted - Victory Dance Initiated!'); });

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:

var form = document.querySelector('form'); function onSubmit(event) { event.preventDefault(); // Onwards with form handling... } // choosing 'addEventListener' or 'attachEvent' - this isn't Sophie's Choice! if (form.addEventListener) { form.addEventListener('submit', onSubmit); } else if (form.attachEvent) { form.attachEvent('onsubmit', onSubmit); }

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:

if (form.checkValidity === undefined) { // JavaScript form validation 🛡️ for old browsers form.addEventListener('submit', function(event) { var isValid = /* your validation logic */; if (!isValid) { event.preventDefault(); alert('Oops! The form misbehaved. Can you please correct it?'); } }); } else { // HTML5 validation, FTW 🎉! form.setAttribute('novalidate', true); }

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:

// forEach acting like a ninja working on each form Array.from(document.querySelectorAll('form')).forEach(function(form) { form.addEventListener('submit', onSubmit); });

For an even more standalone library:

// FormValidator - it doesn't let anything slip through the cracks! function FormValidator(selector, callback) { this.forms = document.querySelectorAll(selector); this.forms.forEach(function(form) { form.addEventListener('submit', function(event) { event.preventDefault(); var isValid = callback(form); if (isValid) { form.submit(); } }); }); } // Usage new FormValidator('form', function(form) { // Validation logic here return true; // Or false based on validity });

Nailing framework-dependent form handling

AngularJS form submission

In AngularJS, ensure the form submission is intently listening within the directive:

app.directive('myForm', function() { return { require: 'form', link: function(scope, element, attrs, form) { element.on('submit', function(event) { scope.$apply(function() { if (form.$valid && scope.customIsValid) { // Past the gates(open for submission) we go... } else { event.preventDefault(); } }); }); } }; });

Tackling React form handling

With React, leverage the onSubmit props to your advantage:

class MyForm extends React.Component { handleSubmit(event) { event.preventDefault(); if (this.isValid(this.state)) { // Time to process form data. Work mode - Activated! } } render() { return ( <form onSubmit={this.handleSubmit.bind(this)}> {/* form elements */} </form> ); } }

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.