In HTML5 we can use the form
attribute on form control elements to have them be part of a form other then the one they're childs of, as described in this answer.
These elements however seem not to be considered when passing the form element to the FormData
constructor, as described on MDN.
Is there a way to have these 'external' controls be included in a way that I then can send the complete form data via a fetch Request?
I am aware, that I could loop through the external elements and append
them to the FormData instance like so
let formData = new FormData(form);
for (const external of document.body.querySelectorAll('[form="' + form.name + '"]')) {
formData.append(external.name, external.value);
}
However I hoped for a more convenient way, especially taking in consideration the extra cases and checks I would have to make it work with radiobuttons etc.
The elements on which you use the form
attribute are included in the FormData
constructor when you pass down the form element. For example:
const form = document.getElementById("myform");
const formData = new FormData(form);
for (const [key, value] of formData) {
console.log(`${key}: ${value}\n`);
}
<form action="/action_page.php" id="myform">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
<input form="myform" type="email" name="email" value="email@email.com" />
As you can see, the email input element, which is outside of the form element, gets included in the form's FormData
.
My guess is that you may have misued the form attribute, if this doesn't help I would suggest you to share some of the code you have wrote in order to make the problem more clear.