I'll preface by saying that I'm very familiar with click events and know I can register a click event on a form submit button as many other answers explain. My question is a level deeper.
Forms can be submitted in other ways than clicking submit: I'm thinking like when a user presses enter while focused on an input/select or even by pressing space or enter while focused on the submit button itself…and I'd like to be able to get a reference to the element that submitted the form.
This answer seemed to have promise, but I'm not exactly sure how to 'see' the values he mentions. I made a codepen to demonstrate. *edit: I updated the codepen to reflect the accepted answer below.
It would also seem that the answer is actually inaccurate in that when a user submits a form, the browser triggers the click event on the first submit in the form, not the first submit after the element that triggered the submit (at least when I ran that Codepen in Chrome/Firefox/Safari).
To give some context for why this is necessary, I'm working on an Asp.NET site where every page's content is encapsulated in a monolithic form. I'm adding an email subscription form to the footer that submits asynchronously…which means I need to do an e.preventDefault()
on the event and also want to avoid accidental submissions if the form is actually being submitted from somewhere else like the search bar up top or a form I wasn't aware of.
The onsubmit event occurs when a form is submitted.
The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript. The method form. submit() allows to initiate form sending from JavaScript.
The onsubmit attribute fires when a form is submitted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With