What Is the Submit Event?
Forms are fundamental to web interaction, enabling users to submit data, create accounts, complete purchases, and communicate with services. At the heart of form handling in JavaScript lies the submit event--a powerful mechanism that fires whenever a user attempts to submit a form.
The submit event is a DOM event that fires on an HTMLFormElement when a form is submitted. Unlike click events on individual submit buttons, the submit event targets the form element itself rather than any specific submit button, providing a unified interface regardless of how the submission was initiated. This architectural design means you attach your event listener to the <form> element, not to buttons, creating a centralized point of control for all form submission scenarios.
The event follows standard DOM event behavior and bubbles up through the DOM hierarchy, allowing for event delegation strategies where a parent element can intercept submit events from multiple forms. This bubbling behavior is particularly useful in single-page applications where forms may be dynamically added or removed, enabling developers to attach a single listener to a container and handle submissions from any form within it without requiring individual listeners for each form element.
1// The submit event fires when:2 3// 1. User clicks a submit button4const form = document.querySelector('form');5form.addEventListener('submit', (event) => {6 console.log('Form submitted!');7});8 9// 2. User presses Enter while focused on a form field10// (handled automatically by the browser)11 12// 3. Programmatic call to requestSubmit()13// form.requestSubmit(); // Fires submit event14 15// NOTE: form.submit() does NOT fire the submit event16// form.submit(); // Direct submission, bypasses eventThe SubmitEvent Interface
The SubmitEvent interface represents the event object passed to submit event handlers. Introduced as part of the HTML Living Standard and available in all modern browsers since September 2021, SubmitEvent inherits from the base Event interface while adding submission-specific functionality.
The Submitter Property
The submitter property is the most distinctive feature of SubmitEvent, providing access to the specific element that initiated the form submission. This property returns an HTMLElement that was clicked or activated--whether a <button>, <input type="submit">, or another submit-triggering element. When the form.submit() method is called directly, the submitter property will be null since no user interaction triggered the submission. This distinction is crucial for applications that need to differentiate between programmatic and user-initiated form submissions.
The submitter property enables powerful patterns such as handling multiple submit buttons on a single form. When a user clicks "Save Draft" versus "Publish," the submitter property reveals which button was activated, allowing conditional logic that routes the submission appropriately without requiring separate event handlers for each button.
1// Method 1: Using addEventListener (recommended)2const form = document.getElementById('myForm');3form.addEventListener('submit', (event) => {4 // Handle submission5 console.log('Form submitted via addEventListener');6});7 8// Method 2: Using onsubmit property9form.onsubmit = (event) => {10 // Handle submission11 console.log('Form submitted via onsubmit');12};13 14// Removing the handler15form.removeEventListener('submit', handlerFunction);16form.onsubmit = null;Preventing Default Form Submission
One of the most important aspects of submit event handling is the ability to prevent the default form submission behavior, allowing JavaScript to take control of the submission process.
Why Prevent Default?
- Single Page Applications: SPA frameworks need to handle navigation without page reloads, making event.preventDefault() essential for maintaining the single-page experience
- Ajax/fetch submissions: Modern apps typically submit forms asynchronously using the Fetch API, requiring prevention of the default browser submission that would cause a page navigation
- Client-side validation: Validate before sending data to the server--preventDefault() allows you to validate inputs and only proceed if all validation passes
- Custom submission handling: Add loading states, analytics tracking, or data transformation before sending data to your backend
By calling event.preventDefault(), you stop the browser's default submission behavior while allowing your custom JavaScript logic to execute. The form remains in place on the page, and you have full control over how data is processed and sent to your server. This pattern is essential for modern web development where seamless user experiences take priority over traditional page reloads.
1const form = document.getElementById('contactForm');2 3form.addEventListener('submit', async (event) => {4 // Prevent default browser submission (page navigation)5 event.preventDefault();6 7 // Validate form data8 const formData = new FormData(form);9 const data = Object.fromEntries(formData);10 11 // Example validation12 if (!data.email || !data.email.includes('@')) {13 alert('Please enter a valid email address');14 return;15 }16 17 // Send data asynchronously18 try {19 const response = await fetch('/api/submit', {20 method: 'POST',21 headers: { 'Content-Type': 'application/json' },22 body: JSON.stringify(data)23 });24 25 if (response.ok) {26 alert('Form submitted successfully!');27 form.reset();28 }29 } catch (error) {30 console.error('Submission error:', error);31 alert('An error occurred. Please try again.');32 }33});Identifying the Submitting Button
Forms often include multiple submit buttons for different actions--such as "Save Draft" and "Publish"--and the submit event's submitter property enables you to distinguish between them. By checking event.submitter, you can determine which specific button triggered the form submission and apply conditional logic based on the user's intent.
The submitter property returns the actual button element that was clicked, so you can compare against its ID using submitter.id, its name attribute using submitter.name, or its value attribute. This pattern is particularly valuable in content management systems where a single form might handle both draft saves and publication, allowing you to route the submission appropriately without maintaining separate forms for each action. Both <button> and <input type="submit"> elements work with this pattern, giving you flexibility in your UI design.
1<form id="postForm">2 <input type="text" name="title" placeholder="Post title">3 <textarea name="content" placeholder="Post content"></textarea>4 5 <!-- Multiple submit buttons with different actions -->6 <button type="submit" name="action" value="publish">7 Publish8 </button>9 <button type="submit" name="action" value="draft">10 Save Draft11 </button>12</form>1const form = document.getElementById('postForm');2 3form.addEventListener('submit', (event) => {4 event.preventDefault();5 6 // Identify which button triggered the submission7 const submitter = event.submitter;8 const action = submitter?.value; // 'publish' or 'draft'9 10 const formData = new FormData(form);11 const data = Object.fromEntries(formData);12 13 if (action === 'publish') {14 console.log('Publishing post:', data);15 // Publish logic16 } else if (action === 'draft') {17 console.log('Saving draft:', data);18 // Save as draft logic19 }20 21 // Use submitter.id for ID-based identification22 // if (submitter.id === 'publishBtn') { ... }23});Always Use addEventListener
Attach event listeners without overwriting existing handlers. Supports multiple listeners and better memory management.
Prevent Default for SPA Forms
Call event.preventDefault() for client-side handling to prevent page navigation in single-page applications.
Validate on Client and Server
Client-side validation improves UX, but server-side validation is essential for security and data integrity.
Handle Errors Gracefully
Provide clear feedback for validation errors and network failures. Log errors for debugging.
Use submitter for Multiple Actions
Leverage the submitter property to differentiate between multiple submit buttons on a single form.
Provide User Feedback
Show loading states during submission and confirm success or failure clearly to users.
Common Pitfalls to Avoid
Understanding common mistakes helps developers write more robust form handling code and avoid frustrating debugging sessions.
Forgetting preventDefault()
The most common mistake in single-page applications is forgetting to call event.preventDefault(). Without this call, the browser will navigate away from the current page, effectively reloading the application and losing any client-side state. This is particularly problematic in SPAs where the form is meant to submit data asynchronously without a full page refresh.
Not Handling Validation Failures
When validation fails, simply returning from the event handler without calling preventDefault() allows the form to submit anyway. Always call preventDefault() first, validate all inputs, and only proceed if validation passes. Additionally, provide clear error messages that guide users toward correcting their input.
Ignoring the submitter Property
When a form has multiple submit buttons, failing to check event.submitter means your code cannot differentiate between different user intentions. This leads to all buttons triggering the same behavior, which is rarely the desired outcome.
Memory Leaks
In dynamic applications where forms may be created and destroyed, failing to remove event listeners when forms are removed from the DOM can cause memory leaks. Always store handler references so they can be removed when components unmount. Following these web development best practices ensures your forms remain performant and reliable.
Using form.submit() When Submit Event Is Needed
The form.submit() method bypasses the submit event entirely, meaning no event handlers will fire. If you need to trigger a submission programmatically while still firing the submit event (and using the submitter property), use form.requestSubmit() instead.
Browser Compatibility
The SubmitEvent interface enjoys broad support across modern browsers including Chrome, Firefox, Safari, and Edge. The submit event itself has been supported since early browser versions. For older browser support, polyfills are available, and feature detection is recommended for edge cases.
Frequently Asked Questions
Sources
- MDN Web Docs: HTMLFormElement submit event - Comprehensive official documentation covering the submit event API, syntax, event type, properties, and examples
- MDN Web Docs: SubmitEvent interface - Official documentation for the SubmitEvent interface including constructor, submitter property, and practical examples
- WHATWG HTML Living Standard - event-submit - Living standard specification for the submit event
- Strapi: Vanilla JavaScript Form Handling Guide - Modern guide covering form validation, submission patterns, and best practices