jQuery Multiple Forms Submit

后端 未结 2 992
暗喜
暗喜 2020-12-03 15:28

I have 4 forms on a page. I know that forms cannot be nested.

相关标签:
2条回答
  • 2020-12-03 15:58

    It's not possible. You can either use serialize() or serializeArray() method for getting forms' data and post them to the server using Ajax:

    Encode a set of form elements as a string for submission.

    $('#send').click(function() {
       var firstFormData  = $('form:eq(0)').serializeArray();
       var fourthFormData = $('form:eq(3)').serializeArray();
       $.ajax({
            url  : '...',
            type : 'post',
            data : firstFormData.concat(fourthFormData)
       }).done(function() {
           // ...
       });
    });
    
    0 讨论(0)
  • 2020-12-03 16:05

    Okay, I could not get .serialize() to work with checkbox array from form4 e.g.

    <input type="checkbox" id="model[]">
    

    I tried to grab checked values but could not get them to serialize together with other input :

    var vals = []
        $('input:checkbox[name="model[]"]').each(function() {
            if (this.checked) {
                vals.push(this.value);
            }
        });
    

    So I went back and did the simpler thing :

    Removed form1, move the text input and the submit button within a <div id="searchbox" style="position:abosulte;top:-100px;left:0px;">My original form1</div> inside form4.

    Put a placeholder <div id="placeholder" style="position:relative;"></div> above form2 and 3 where form1 used to be.

    Place a javascript above :

    $(document).ready(function(){
        $("#searchbox")
        .appendTo("#placeholder");
    });
    

    to move the text input and submit button to position them absolute and relative to the placeholder div.

    This way I reduced them to 1 form (which is what its intention anyways), does not rely on javascript to manipulate any data, and does not require me to do the tandem serialization on both forms.

    0 讨论(0)
提交回复
热议问题