JavaScript Reference ยท DOM: Events
The submit event
Reference for the form submit event: intercept submission, read FormData, use SubmitEvent.submitter, run validation and know the difference from requestSubmit().
The submit event fires on a <form> element when the user submits it: by pressing a submit button, by pressing Enter in a text field, or when your code calls form.requestSubmit(). It fires before the browser sends the data, and it is cancelable. Calling preventDefault() stops the page from navigating, which is how single-page apps handle forms with JavaScript.
Listen for submit on the form, not for click on the button. That way you also catch keyboard submissions, and the browser's built-in validation runs first.
form.addEventListener("submit", (event) => { event.preventDefault(); const data = new FormData(form); });
Try it
Syntax
form.addEventListener("submit", (event) => { /* SubmitEvent */ });
Event properties
| Property | Description |
|---|---|
submitter |
The button or input (type="submit" or image) that triggered submission, or null if the form was submitted another way, for example with requestSubmit() without arguments. |
target |
The form. |
cancelable |
true. |
bubbles |
true. |
Usage notes
- Validation first. If a control fails constraint validation (
required,pattern,minand so on), the browser shows its messages and does not firesubmit. Theinvalidevents fire instead. Addnovalidateon the form to skip built-in validation. form.submit()skips the event. Callingform.submit()sends the form directly with nosubmitevent and no validation. Useform.requestSubmit()when you want the normal path.- Multiple submit buttons. Use
event.submitter(or itsnameandvalue) to know which button was used.new FormData(form, event.submitter)includes that button's value too. - Name your controls.
FormDataonly includes controls that have anameattribute, and skips unchecked checkboxes, disabled controls and unselected radios. - Prevent double submissions. Disable the submit button, or set a flag, while a request is in flight.
- Keep the action. Give the form a real
actionandmethodso it still works if JavaScript fails, and callpreventDefault()only when your script is ready. - Sandboxed previews. In the live examples on this page nothing is sent to a server; the handler only prints the data.
- File uploads. Forms with
<input type="file">needenctype="multipart/form-data"for a native post; withfetch()pass theFormDataobject directly and do not set theContent-Typeheader yourself.
Browser support
The submit event works in all browsers. requestSubmit() and event.submitter are supported by all current browsers; check a compatibility table if you support older ones.