\n","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Anton Shumikhin","url":"https://explain.codes//author/anton-shumikhin"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2024-11-01T22:45:04.952Z","dateModified":"2024-11-01T22:45:06.559Z"}
Explain Codes LogoExplain Codes Logo

How do I cancel form submission in submit button onclick event?

javascript
event-listeners
form-validation
ajax
Anton ShumikhinbyAnton Shumikhin·Nov 1, 2024
TLDR

Stop form submission by using the event.preventDefault() method within the onclick event:

<button type="submit" onclick="event.preventDefault();">Submit</button>

Or, utilize a handler function within the form's onsubmit method, returning false when the form input is not valid:

<form onsubmit="return !isValidForm();"> <button type="submit">Submit</button> </form> <script> function isValidForm() { // Replace the next line with your validation logic return Math.random() > 0.5; // (Just a little Russian roulette joke for you 🎲) } </script>

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:

function isValidForm() { // Your validation logic here return document.getElementById('myForm').elements.input.value !== 'bomb'; // Not into explosive situations }

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:

document.getElementById('myForm').addEventListener('submit', function(e) { if (!isValidForm()) { e.preventDefault(); // <-- The red STOP sign 🛑 } });

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:

document.getElementById('myForm').addEventListener('submit', function(e) { e.preventDefault(); if (isValidForm()) { sendAjax(); // Off it goes! } });

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:

$('#myForm').submit(function(e) { if (!isValidForm()) { e.preventDefault(); // jQuery just helped us dodge a bullet! 🚀 } });

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:

function btnClick(e) { if (!validData()) { e.preventDefault(); // "Sorry data, you're not on the list. Entry denied!" 🚷 } // If valid data, the event continues normally }

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:

document.getElementById('mySubmitBtn').onclick = function(e) { return btnClick(e); };

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:

function submitFormWithAjax(data) { // AJAX post logic... // Updating the page based on response // The user is left none the wiser! }