Explain Codes LogoExplain Codes Logo

Submit form after calling e.preventDefault()

javascript
form-validation
event-handling
best-practices
Anton ShumikhinbyAnton Shumikhin·Aug 31, 2024
TLDR

Programmatically submit a form with the submit() method after employing custom logic:

document.getElementById('myForm').onsubmit = function(e) { e.preventDefault(); // Halt auto submission // Custom logic like a boss if (allValidationsPass()) { this.submit(); // Force submission like a pro } };

Apply this approach when you've intercepted the default submission for some pre-processing or validation, and now wish to proceed with the submit.

Stopping and starting form submission

Effective form validation promotes usability and ensures data integrity. Accomplish this by establishing stringent validation procedures before submission. Use e.preventDefault() in occasions where form submission needs to be interrupted. Let's adapt the previous snippet to a larger, but efficient, form-handling function:

document.getElementById('myForm').addEventListener('submit', function(e) { e.preventDefault(); // Start by stopping the submission. Ironic, isn't it? let isValid = true; // Initial green flag for form submission // Custom validation logic document.querySelectorAll('.attendee').forEach(function(el) { if (!el.value.trim()) { // El.trim() to remove sneaky white spaces alert('Please enter the name for each attendee.'); el.focus(); // Highlight the problem like a detective isValid = false; // Red flag! Abort mission! return; // Not the end of the world. Just the end of this iteration } // Use the vanilla JS version of next() let entree = el.nextElementSibling; if (!entree.value) { alert('Please select an entree for each attendee.'); entree.focus(); // Magic spell to reveal where the problem lies isValid = false; // Red alert! Red alert! return; } }); // If all validations pass, submit the form like a boss if (isValid) { e.currentTarget.submit(); // Acing form submission without the jQuery hassle } });

Every elaborate form submission requires scrupulous input validation. This detailed digression showcases how you can thoroughly inspect each input before proceeding to form submission.

Dissecting native and jQuery submit

Differentiating the native JavaScript method from the jQuery counterpart can save you from potential headaches:

  • Native submission (element.submit()): Direct and unaffected by any previously initialized jQuery bindings. Simply submits the form without triggering any submit event handlers.
  • jQuery submission ($(element).submit() or .unbind().submit()): Incites any jQuery submit event handlers unless unbound, which can lead to undesirable consequences.

In an environment where you're using jQuery but want a clean form submission without invoking any handlers, use the native submit() method to avert conflicts:

// Within a jQuery event handler $('form').on('submit', function(e) { if (shouldPreventDefault) { e.preventDefault(); // Additional code shenanigans } else { this.submit(); // Bypass jQuery mumbo jumbo with native submission } });

Here, we directly invoke the form's submit() method rather than unbinding the event. Reduces complexity, improves readability, and makes code more into the realm of elegance.

The secrets to form submission mastery

Golden rules to smoother form handling

Alerts and focus: Alert the user only when needed and use .focus() judiciously to direct users without overwhelming them.

Validation status: Use a boolean flag like isValid to keep track of the form state. This avoids premature termination of iteration loops like .each() or forEach.

Code cleanup for the win

Remove redundant code: .unbind('submit') may make things complex without any tangible benefit. Code cleanup can do wonders for readability and overall code health.

Immediate prevention: Call e.preventDefault() as early as possible in your event handler. Clear intent, controlled outcomes.

User experience - the holy grail

Direct attention: Connect the user with the first invalid input. Creating a streamlined path for correction can drastically enhance user experience.

Uniform validation: Utilize loops to validate each input, creating consistency across all form inputs, and making error handling more fault-tolerant and manageable.

Visualization

Calling e.preventDefault() is akin to pausing a train before it reaches its destination—aka the form submission depot.

| Action | Train Analogy | Form Behaviour | | --------------------- | --------------------- | ------------------------------ | | e.preventDefault() | 🚄⏸️ (Train paused) | 📃🚫 (Form submission halted) | | Input validation | 🛤️🔎🔧 (Track inspected) | 🖊️✔️ (Inputs verified) | | Resume submission | 🚄▶️🛤️🏁 (Train resumes) | 📃✅ (Form submission resumes) | | Invalid input found | 🛤️❌🚧 (Obstruction) | 🖊️❌ (Input validation error) | | Focus on error | 🛤️🔍💡 (Signal detected)| 🖊️👀 (User alerted to error) |

Upon resuming, both the train and the form crucially reach their destinations. 🚄➡️🏁➡️🌐