Current Redemption
Current Redemption

Reputation: 199

JS - submit more than one form with one button

I'm trying to submit more than 1 form and decided to do so with JS. (at least the subbmiting part) so i have this simple form:

<form action="test/submit.php" method="post" id="submit_template">
    <center>
        <input type="hidden" id="payment" name="DB_Table" value="payment">
            <div id="template" class="collapse.toggle">
                <input type="text" placeholder="Full Name" name="Full_Name">
                <input type="text" placeholder="Full Name" name="Full_Name">
            </div>
    </center>
</form>

I created a JS to change the ID for that form id - such as "submit_template1...2..." etc and the button looks like this:

<button id="submit" type="button" name="submit" value="submit" class="button=1" onclick="submitForms()">Submit</button>

i tried to create a JS for subbmitting all forms the code looks like this:

submitForms = function()
{
    for(i = 0 ; i < document.getElementsByTagName("form").length ; i++)
    {
        document.getElementById("submit_template" + i).submit();
    }
}

when i have more than 1 form it get the following error: Uncought TypeError: Cannot read property 'submit' of null at submitForms (:106) at HTMLButtonElement.onclick

funny thing is that if i go to the F12 console and do something like: var i = 1 document.getelementbyid("submit_template" + i).id

it works perfectly...

any ideas?

Thanks in Advance.

Upvotes: 0

Views: 65

Answers (2)

Quentin
Quentin

Reputation: 943470

When you submit a form the browser makes an HTTP request to the form's action and navigates to it.

Under normal circumstances, you can't navigate to multiple pages at the same time: You only have one viewport.

When you try, it cancels the previous form submission.

If you want to navigate to multiple places at the same time then you need multiple viewports. One way to achieve that would be to have an <iframe> for each <form> and set the target attribute in each. That way the the form submission doesn't trigger navigation away from the page the form is on.

Another approach would be to not submit the forms at all, but to make all the HTTP requests with JavaScript (e.g. fetch or XMLHttpRequest) so there is no navigation at all.

You could also redesign the forms so you have a single form that submits all the data in one go.

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14904

Why dont u do it like this

 for(i = 0 ; i < document.getElementsByTagName("form").length ; i++)
{
    document.getElementsByTagName("form")[i].submit();
    document.getElementsByTagName("form")[i].preventDefault();
}

Upvotes: 0

Related Questions