How to do something before form submission?
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:
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
:
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:
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:
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:
This setup allows you to run complex logic or async tasks without tying directly with the onboard form's submit
event.
Was this article helpful?