Determine which element triggered a form submit event
You can use document.activeElement
This will work for clicks and when the user tabs to a button and hits the enter button.
Listen for the submit event on the form, then inside of the callback, reference document.activeElement
, it will be the button that the user clicked or tabbed to.
Example: http://codepen.io/anon/pen/KVoJrJ
The submit event of a <form>
element actually contains a reference to the submitter
:
https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/submitter
form.onsubmit = (event) => {
const formElement = event.target;
const formSubmitter = event.submitter;
console.log("The form element itself", formElement);
console.log("The submitter of the form (usually an HtmlInputElement)", formSubmitter);
const formData = new FormData(formElement);
if(formSubmitter) formData.set(formSubmitter.name, formSubmitter.value);
fetch(formElement.action, {
method: formElement.method,
body: formData,
})
event.preventDefault();
}
Note: check the compatibility of this feature.