How do I cancel form submission in submit button onclick event?
Stop form submission by using the event.preventDefault()
method within the onclick
event:
Or, utilize a handler function within the form's onsubmit
method, returning false
when the form input is not valid:
Patterns for preventing form submission
Sometimes clicking the submit button is just like clicking an eject button in a fighter jet; everything goes south very quickly. We want to ensure that the eject button (form submission) only triggers if everything is clear for launch.
Form validation logic
Moving validation logic into a function such as isValidForm()
enhances readability (no need for 20/20 vision) and maintainability (less hair pulling). Here's a basic pattern:
Friendly JavaScript with event listeners
Inline JavaScript is like pineapple on pizza; some people swear by it, others feel it's an abomination. For those who fall in the second camp, we use the addEventListener()
method:
Adding a dash of AJAX
Once the default submit action is prevented, we can then buckle up for some AJAX action to send data without a page reload:
Third-party library handling
When JavaScript feels like trying to solve a Rubik's cube blindfolded, libraries like jQuery can remove the blindfold. Its submit
handler allows us to prevent form submission in a more aesthetic manner:
Crafting validation logic
Form validation logic is like your personal bouncer at the club door; it ensures only the right data gets in.
Button-directed form submission control
You can directly control form submission inside the onclick
event of a button. In other words, we're giving the green or red signal right at the button click:
Pre-submit event captures
You might want to capture important events right before the form data sprints away to the server. Doing so allows for minute checks or last-second adjustments:
AJAX for a flawless user experience
Simulation is the best form of flattery, and AJAX allows us to simulate a page refresh. This leaves the user in the comfortable illusion of a static page while the form data is processed:
Was this article helpful?