Explain Codes LogoExplain Codes Logo

How to do something before form submission?

javascript
async-await
javascript-promises
form-validation
Alex KataevbyAlex Kataev·Dec 9, 2024
TLDR

Catch form submission event in JavaScript by setting an event listener. Employ event.preventDefault() inside your function to stop the form submission temporarily. Execute your required pre-submit tasks, then manually resume submission with this.submit(). Here's the code in short:

document.querySelector('#myform').addEventListener('submit', function(event) { event.preventDefault(); // Hold on! Let's not submit yet // Do your pre-submit magic here // Let's proceed with the submit: this.submit(); });

This template allows you to run your own custom tasks like validations or data manipulations before completing the form submission.

Comprehensive guide to the pre-submit

Asynchronous or synchronous tasks: choose your fighter

While implementing pre-submit actions, sometimes it's either synchronous, like form validations, or asynchronous, like a server-side API call. Synchronous tasks are easy-peasy - just call this.submit() once you're done. But for the async ones, you've to use JavaScript promises or async/await syntax to ensure submission occurs only after the async tasks are all done and dusted.

Old jQuery can learn new tricks

If you're riding on the jQuery wagon, you might want to use $('#myform').on('submit', function(event)) to avoid those deprecation warnings and stick with trendy best practices.

Invalidation? Here’s your validation

Consider a beforeSubmit function as the main container for all your pre-submit validation checks or tasks. If all conditions are good to go, return true from the function, else false:

function beforeSubmit() { // Our validation and pre-submit checks are here if (validFormConditions()) { return true; } else { return false; } } $('#myform').on('submit', function(event) { event.preventDefault(); if (beforeSubmit()) { this.submit(); } });

This provides a clean and reusable structure for your code. Like Marie Kondo's mantra - it sparks joy!

Not all superheroes wear submit buttons

Sometimes, things like a click on a different element can trigger form submission. So, if submit button ain't the only hero in your code, bind your pre-submit actions to the trigger with style:

$('#mytrigger').on('click', function() { if (beforeSubmit()) { $('#myform')[0].requestSubmit(); } });

And keep in mind, requestSubmit() might need a polyfill for older folks like Safari.

Plain HTML5 and JavaScript: Power Players

It's time you capitalized on the power of HTML5 and JavaScript:

  • Use HTML5 form constraint validation API for enforcing mandatory fields and validating the data format.
  • Jazz it up with JavaScript by showing real-time validation messages or performing custom checks.

Inform when you perform

After running preventDefault(), the form won’t submit. So, here's a neat trick to notify users about it:

document.getElementById('myform').addEventListener('submit', function(event) { if (!isFormValid()) { event.preventDefault(); displayError('Hey! Please fix the errors to give a green light for submission!'); // DisplayError: Your knight in shining armor to inform users } });

Hat-trick with button types

If you feel rebellious, switch your submit button to a type="button" and take reins of form submission in your hands:

<button type="button" id="customSubmit">Submit</button> $('#customSubmit').on('click', function() { if (beforeSubmit()) { $('#myform')[0].requestSubmit(); // With power, comes great flexibility! } });

This setup allows you to run complex logic or async tasks without tying directly with the onboard form's submit event.