When I listen to a <form>
's submit
event, and get the form's FormData
, e.g. to submit it via an XHR, the submit button's data is missing:
<form>
<input type="text" name="x" value="foo" />
<input type="hidden" name="y" value="bar" />
<button type="submit" name="submit1" value="bar">submit1</button>
<input type="submit" name="submit2" value="submit2" />
</form>
FormData will have x
and y
, but neither submit1
nor submit2
. Try it in a Pen. It should I would like it to contain one of them, namely the one that triggered the submit -- just like the data that would be sent to action
.
I could do something onsubmit
, like
form.onsubmit = function (evt) {
var fd = new FormData(form);
fd.append(evt.submitter.name, evt.submitter.value);
// process fd...
});
BUT SubmitEvent.submitter is fairly new, notably no IE, and only Safari's TP at the time of writing.
Is there a way to get the submit into FormData without doing a workaround like listening to all the form's inputs' click events and creating, say, hidden inputs with their data?
After the accepted answer, I did implement a "polyfill":
document.querySelectorAll('form').forEach(function (form) {
// query might miss <button>s without @type
form.querySelectorAll('[type="submit"]').forEach(function (submit) {
submit.addEventListener('click', function () {
var input = document.createElement('input')
input.setAttribute('type', 'hidden')
input.setAttribute('name', this.name)
input.setAttribute('value', this.value)
this.form.appendChild(input)
})
})
})
Is there a way to get the submit into FormData without doing a workaround like listening to all the form's inputs' click events and creating, say, hidden inputs with their data?
No.
SubmitEvent.submitter
is the feature that was added to take away the need for separate click events.