Explain Codes LogoExplain Codes Logo

Intercept a form submit in JavaScript and prevent normal submission

javascript
event-handling
form-validation
security
Alex KataevbyAlex Kataev·Feb 24, 2025
TLDR

Here's the quick solution: intercept the form's submit event using addEventListener and halt its execution with preventDefault().

document.querySelector('form').addEventListener('submit', event => { event.preventDefault(); // Keep calm and stop execution });

Blocks the form's original submission, clearing the way for custom behaviour, such as AJAX calls.

Detailed explanation and case handling

Best practice across different browsers

In the funny world of the web, not all browsers sing the same song. To make sure your code works across all browsers, use the following:

var form = document.getElementById('myForm'); function handleForm(event) { event.preventDefault(); // Gotcha! Stopping you right there. // Additional code here } if (form.attachEvent) { form.attachEvent('submit', handleForm); // Because, grandma needs love too (legacy browsers) } else { form.addEventListener('submit', handleForm); // Modern browsers, assemble! }

This snippet ensures compatibility across browsers using attachEvent for older browsers when addEventListener is not an option.

Handling the sneaky return key

Users often hit the return key to submit forms. Here's how we handle this tricky devil:

form.addEventListener('keypress', function(event) { if (event.keyCode === 13 || event.which === 13) { event.preventDefault(); // Nice try, Return Key. // Handle submit } });

This portion prevents default form submission via the return key. Trick foiled, your custom logic can now act.

Enhancing form security

Security is critical. To enhance the security of your submission process, consider adding hidden fields such as CSRF tokens:

function addCSRFToken() { var hiddenField = document.createElement('input'); hiddenField.setAttribute('type', 'hidden'); hiddenField.setAttribute('name', 'csrf_token'); hiddenField.setAttribute('value', 'your_secure_token'); document.getElementById('secureForm').appendChild(hiddenField); } window.addEventListener('DOMContentLoaded', (event) => { addCSRFToken(); // Look, mum, no hands! We're secure now. });

This enhances security by adding hidden fields with security tokens before submission.

Resources

  1. Event: preventDefault() method - Web APIs | MDN — Dive deeper into canceling events.
  2. HTMLFormElement: submit() method - Web APIs | MDN — Uncover the secrets of programmatic form submission.
  3. Client-side form validation - Learn web development | MDN — Learn the art of client-side form validation.
  4. Forms: event and method submit — Master the handling of submit events in JavaScript.
  5. submit event | jQuery API Documentation — Decipher jQuery's submit event with this comprehensive guide.
  6. Fetching data from the server - Learn web development | MDN — Fetch, boy! Learn how to fetch data with modern web APIs on this extensive guide.