Jquery - Submit all forms by one button

前端 未结 2 1126
臣服心动
臣服心动 2021-01-03 04:46

Html:

..
相关标签:
2条回答
  • 2021-01-03 05:18

    I didn't test it but try this one:

    $("#allsubmit").on("click", function(){
        $('.allforms').each(function(){
            $(this).submit();
        });
    }); 
    

    Note that all of your forms have to have class="allforms" attribute

    0 讨论(0)
  • 2021-01-03 05:34

    Form submission is a synchronous action, so when you submit a form and then 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 :)
    0 讨论(0)
提交回复
热议问题