Handling Submit Buttons and Multiple Actions
What you'll learn: How to detect which submit button was clicked and handle different form actions from a single form.
The Challenge
Sometimes you need multiple submit buttons in one form—like "Save Draft" vs "Publish" or "Update" vs "Delete". When the user clicks submit, you need to know which button they pressed to take the appropriate action.
How It Works
When a form is submitted, the event object contains a submitter property that references the specific button that triggered the submission. You can check this button's attributes to determine what action to take.
Here's a pattern using what you've learned about preventing default submission and FormData:
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
// Identify which button was clicked
const submitter = event.submitter;
const action = submitter.value; // or submitter.name
const formData = new FormData(form);
if (action === 'save-draft') {
// Handle draft save
console.log('Saving draft...');
} else if (action === 'publish') {
// Handle publish
console.log('Publishing...');
}
});
Your HTML might look like:
<form>
<input type="text" name="title">
<button type="submit" value="save-draft">Save Draft</button>
<button type="submit" value="publish">Publish</button>
</form>
Think of It Like This
It's like a remote control with different buttons—each button on the remote (form) does something different, but they all use the same device. The submitter tells you which specific button was pressed.
Key Takeaway: Use event.submitter to detect which submit button was clicked, then branch your logic based on the button's value or name attribute to handle multiple form actions.