Explain Codes LogoExplain Codes Logo

Javascript code to stop form submission

javascript
form-validation
event-listeners
cross-browser-compatibility
Nikita BarsukovbyNikita Barsukov·Aug 30, 2024
TLDR

To halt the form submission with JavaScript, we add an event listener to the form's submit event and call event.preventDefault():

document.querySelector('form').addEventListener('submit', event => event.preventDefault());

This snippet uses querySelector to target the form and preventDefault function to stop the form submission. It's the JavaScript equivalent of a red traffic light for your form.

Form validation for submission prevention

First, it's crucial to validate the form data before submission. This isValidForm() function assures our form complies with any requirements. It's like our data's very own spellcheck.

document.querySelector('form').addEventListener('submit', function(event) { if (!isValidForm(this)) { event.preventDefault(); // It appears there's a spelling mistake, let's not submit this! return false; // Stops any accidental form submissions } // If the form passes our rigorous spellcheck, submit away! });

If validation fails, we can be polite and direct the user back to the form page using window.history.back(). It's like our form's GPS.

if (!isValidForm(this)) { window.history.back(); // Form validation failed; turns on the GPS event.preventDefault(); return false; // Because once wasn't enough }

Custom button to control form submission

Aside from the usual submit button, we can use an input typed as "button" to customise our form submission process:

<input type="button" value="Submit" onclick="submitForm()" /> <!-- This button is more than it seems! -->
function submitForm() { var form = document.querySelector('form'); if (isValidForm(form)) { // Form passes spellcheck, submit away! form.submit(); } } // This button doesn't submit, it previews it!

Ensuring cross-browser compatibility

Event handling and form submission must ensure cross-browser compatibility. Here's how you can write a compatibility-flexible code:

function attachEvent(element, eventName, handler) { if (element.addEventListener) { element.addEventListener(eventName, handler); } else if (element.attachEvent) { element.attachEvent('on' + eventName, handler); // for older IE versions. Yes, they still exist! } } attachEvent(document.querySelector('form'), 'submit', function(event) { // Your form submission handling logic event.preventDefault(); // Prevent submission because traffic rules apply to all browsers! });

This function is like a linguist translating modern speak to an older dialect to ensure that everyone understands.

Advanced techniques

Let's now look at several advanced techniques we can use for controlling form submissions.

Working with libraries

Using libraries like Dojo? Use dojo.connect to attach event listeners:

dojo.connect(dijit.byId('myForm'), 'onsubmit', function(event) { event.preventDefault(); // Traffic rules still apply! // Your validation logic here });

Legacy code handling

Some older code may depend on the return value of the event handler:

<form onsubmit="return validateForm();"> <!-- Old code, new tricks! -->
function validateForm() { if (conditionsNotMet) { return false; // Stops form submission } return true; // Everything is awesome, submit the form! }

Control of navigation post submission prevention

Need to take the user away to a different page after stopping the form submission? Redirect them:

event.preventDefault(); window.location.href = '/another-page'; // Where we're going, we don't need forms!