Merge values from two forms on submit

前端 未结 9 901
甜味超标
甜味超标 2020-11-29 18:12

I have two forms on one html page. Using jQuery, is it possible to have the data from both forms go into the POST data when the first is submitted?

相关标签:
9条回答
  • 2020-11-29 18:31

    While the other answers address the question you asked, it may be worth considering why you have 2 separate forms, if you want to send the contents of both forms whenever the user submits one.

    If you are using 2 different forms to separate them visually, a better approach may be to use CSS to place the elements on the screen as you desire. That way, you are not relying on the presence of Javascript to ensure that your forms are populated correctly.

    0 讨论(0)
  • 2020-11-29 18:33

    Using serialize to combine forms and submit using ajax was working for me until I added an "export" button (to send data as an excel file). For that I needed to do a full postback. So I ended up with this method. It chooses the appropriate merge technique, and fixes some of the issues with buttons, selects and textareas along the way:

    $("body").on("submit", ".combineForm", function () {
    
        var frm = $(this);
        var action = frm.attr("action");
        var method = frm.attr("method");
        var target = frm.data("updateTarget");
    
        var combined = $(".combineForm");
    
        //get the submit button that was clicked
        var btn = $(this).find("button[type=submit]:focus");
        var btnName = btn.attr("name");
        var btnValue = btn.attr("value");
    
        //create an in memory form to avoid changing the existing form
        var f = $("<form action='" + action + "' method='" + method + "'/>")
    
        //Browsers send the name and value of the clicked button but serialize, clone and our copy can't
        //So add a hidden field to simulate browser behaviour
        if (btnName)
            f.append("<input name='" + btnName + "' type='hidden' value='" + btnValue + "' />")
    
        if (btnValue === "export") {//exporting to a file needs full submit
    
            //merge forms with class 'combineForm' by copying values into hidden inputs
            // - cloning doesn't copy values of select or textareas
            combined.find(":input").not("submit").each(function () {
                var inp = $("<input name='"
                            + $(this).attr("name")
                            + "' type='hidden' value='"
                            + $(this).val() + "' />")
                f.append(inp);
            });
    
            f[0].submit();
            return false;
        }
    
        //merge forms for ajax submit
        var data = combined.serialize() + "&" + f.serialize();
        $.ajax({
            url: action,
            type: 'POST',
            data: data,
            dataType: "html",
            success: function (html) {
                $(target).html(html);
            }
        });
    
        return false;
    });
    
    0 讨论(0)
  • 2020-11-29 18:35

    Another way to merge your own data into form serialize

            var data = {};
            data['key'] = 'value';
    
            e.preventDefault();
            $.ajax({
                url : url,
                dataType : 'json',
                type : 'post',
                data : $(this).serialize() + '&' + $.param(data),
                success : function(data) {
    
                },
                error : function() {
    
                }
            });
    
    0 讨论(0)
  • 2020-11-29 18:47

    This is a clean JavaScript approach for merging two forms. I test it with a POST request with Prototype and jQuery and it works. This is the thing:

    var data1 = document.getElementById('form1').serialize();
    

    NOTE: form1 is form's id .You need to set it within <form id="form1"></form >

    var data2 = document.getElementById('form2').serialize();
    

    NOTE: form2 is form's id. You need to set it within <form id="form2"></form >

    Now you have two vars and two serialized data (arrays). You can easily merge them. Your form will have assoc. array and you can get a problem when you try using concat function.

    var mergeddata = data1 + '&' + data2;
    

    This is it! You can easily send them through ajax call. For example, Prototype.js:

     new Ajax.Request(url, {
                            method: 'post',
                            parameters: mergeddata, ...
    
    0 讨论(0)
  • 2020-11-29 18:48

    One approach is to copy all of form2's inputs into form1 once the data validation check succeeds. This assumes you are not doing an AJAX submit.

    // new onsubmit function for form1
    function form1_onsubmit()
    {
        if (!EntryCheck()) return false; 
    
        $('#form2 :input').not(':submit').clone().hide().appendTo('#form1');
    
        return true;
    }
    

    If you wanted to cater for hitting submit twice, possibly because of submit fail from the server, we would need to remove any copied inputs before copying in new ones.

    // new onsubmit function for form1
    function form1_onsubmit()
    {
        $('#form1 :input[isacopy]').remove();
    
        if (!EntryCheck()) return false; 
    
        $('#form2 :input').not(':submit').clone().hide().attr('isacopy','y').appendTo('#form1');
    
        return true;
    }
    
    0 讨论(0)
  • 2020-11-29 18:49

    I wrote a function that Merge Two Complexe, cames from different Forms, as:

    // Each Object came from serializeArray()
    var obj = $('form').serializeArray();
    obj = JSON.stringify(obj);
    obj = JSON.parse(obj);
    

    // Example

    obj1 = [
            { name: 'name1', value: 'value1'},
            { name: 'name2', value: 'value2'},
            { name: 'name3', value: 'value3'}
        ];
    
    obj2 = [
            { name: 'name4', value: 'value4'},
            { name: 'name2', value: 'value5'},
            { name: 'name1', value: 'value6'}
        ];
    
    
    function mergeTwoJsonObj( obj1, obj2 ){
    
        var obj3 = [];
        for (var index in obj1) {
            obj = {name: obj1[index].name, value: obj1[index].value};
            obj3.push(obj);
        }
        for (var index in obj2) {
            obj = {name: obj2[index].name, value: obj2[index].value};
            var isExist = false;
            var existAt;
    
            for (var j in obj3) {
                if( obj3[j].name === obj2[index].name){
                    isExist = true;
                    existAt  = j;
                    break;
                }
            }
    
            if(!isExist) {
                obj3.push(obj);
            } else {
                obj3[j].value = obj2[index].value;
            }
    
        }
    
        obj3 = JSON.stringify(obj3);
        obj3 = JSON.parse(obj3)
    
        return obj3;
    
    }
    

    For the example obj1, and obj2 it returns:

    // Example

     obj3 = [
            { name: 'name1', value: 'value6'},
            { name: 'name2', value: 'value5'},
            { name: 'name3', value: 'value3'},
            { name: 'name4', value: 'value4'}
        ];
    

    I wish it helps

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