'how to fire off multiple forms/submit buttons at the same time at the click of one button
I have some tabs, each containing their own form and their own submit button. I want to fire off all the forms and send requests for each form at the click of one button. That one button should essentially click each individual submit button for each form (in this case that button would be the button with class "submit_all". The html:
div class="tab-content" id="tab_content_one"
div id="#tab1" class="tab-pane fade in active"
= form_tag({ action: "route1" }, method: method)
.form-group
textarea.form-control name="words"
input.btn.btn-primary type="submit" class="submit"
div id="tab2" class="tab-pane fade"
= form_tag({ action: "route1" }, method: method)
.form-group
textarea.form-control name="words"
input.btn.btn-primary type="submit" class="submit"
div id="tab3" class="tab-pane fade"
= form_tag({ action: "route1" }, method: method)
.form-group
textarea.form-control name="words"
input.btn.btn-primary type="submit" class="submit"
input.btn.btn-primary type="submit" class="submit_all" onclick="goBack()"
I tried using javascript to retrieve all the submit buttons for each of the forms and iterating through and clicking each submit button however that did not work. It ended up only firing off the final form.
function goBack() {
var submit2 = document.getElementsByClassName('submit')
console.log(submit2)
for (i=0; i<=(submit2.length); i++){
submit2[i].click()
}
Am I doing something wrong? and how else can I go about this?
Solution 1:[1]
If you send a form.submit()
-event (or button.click()
on the submit button) on all forms, only one form may be submitted, depending on how the forms are build.
To get the data from all forms you can gather them with new FormData(FormElement) and serialize them using [...formData.entries()]
.
submitAll.onclick = () => {
const data = [ ...new FormData(form1).entries(), ...new FormData(form2).entries() ];
// place your logic here...
// for example a fetch() or websocket.send() request
console.log(data);
}
<form id="form1" onsubmit="event.preventDefault(); return false;">
<input type="text" name="customForm1Text" value="something">
<input type="submit">
</form>
<form id="form2" onsubmit="event.preventDefault(); return false;">
<input type="text" name="customForm2Text" value="text">
<input type="number" name="customForm2Number" value="1">
<input type="date" name="customForm2Date">
<input type="submit">
</form>
<button id="submitAll">Submit both forms at once</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Christopher |