Vasilis Greece Vasilis Greece - 3 days ago 5
Javascript Question

Jquery - Submit all forms by one button

Html:

<form class="allforms" method="POST" action="/auth/myaccount/personal">
<input type="hidden" name="_method" value="PATCH">
...
</form>

<button id="allsubmit" class="btn btn-info">Continue</button>


jquery:

$(document).ready(function(){
$("#allsubmit").click(function(){
$('.allforms').submit();
});
});


I have 3 forms in my html code like above.
My button is out of any my forms.
How to have one submit button for all my forms. I tried the click function but it doesn't work. Why?

Answer

Form submission is a synchronous action, so when you submit a form and them immediately submit a different form in your page, the first form's submission is canceled.

What you can do instead is make sure the forms are submitted asynchronous (using ajax):

$(function() {
    $("#allsubmit").click(function(){
        $('.allforms').each(function(){
            valuesToSend = $(this).serialize();
            $.ajax($(this).attr('action'),
                {
                method: $(this).attr('method'),
                data: valuesToSend
                }
            )
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form class="allforms" method="POST" action="">
  <input type="hidden" name="_method" value="PATCH1">
  <input type="submit" />
</form>

<br />
<form class="allforms" method="POST" action="">
  <input type="hidden" name="_method" value="PATCH2">
  <input type="submit" />
</form>

<br />
<form class="allforms" method="POST" action="">
  <input type="hidden" name="_method" value="PATCH3">
  <input type="submit" />
</form>

<br />
<button id="allsubmit" class="btn btn-info">Continue</button>

A few notes

  1. This will not work with forms that have file-uploading (enctype="multipart/form-data")
  2. You need to decide what to do after the submission is done (because nothing in the page will change).
  3. You can't submit forms in stackoverflow-snippets, so don't try to run this here :)
Comments