jQuery 提交时合并来自两个表单的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2341001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:17:22  来源:igfitidea点击:

Merge values from two forms on submit

jqueryhtml

提问by Brian

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?

我在一个 html 页面上有两个表单。使用 jQuery,是否可以在提交第一个表单时将两个表单中的数据都放入 POST 数据中?

采纳答案by Lachlan Roche

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.

一种方法是在数据验证检查成功后将所有 form2 的输入复制到 form1 中。这假设您没有执行 AJAX 提交。

// 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;
}

回答by Sagi

jQuery serialize supports multiple form elements, So it is possible to do:

jQuery serialize 支持多个表单元素,所以可以这样做:

$('#form1, #form2').serialize();

And for your case, you can do:

对于您的情况,您可以执行以下操作:

$('#form1').submit(function() {
    var action = $(this).attr('action');
    if (!EntryCheck()) return false;
    $.ajax({
        url  : action,
        type : 'POST',
        data : $('#form1, #form2').serialize(),
        success : function() {
            window.location.replace(action);
        }
    });
    return false;
});

回答by iisisrael

Lachlan Roche's solution only copies the elements, but not the values. This will take care of values as well, and can be used to handle either form submission:

Lachlan Roche 的解决方案只复制元素,而不复制值。这也将处理值,并可用于处理任一表单提交:

<script type="text/javascript">
  var submitter = {
    combine: function (form1, form2) {
      $('#' + form1 + ' :input[isacopy]').remove();
      $('#' + form2 + ' :input').not(':submit').not('textarea').not('select').each(function() { $(this).attr('value', $(this).val()); });
      $('#' + form2 + ' textarea').each(function() { $(this).text($(this).val()); });
      $('#' + form2 + ' select').each(function() { $('option[value!="' + $(this).val() + '"]', this).remove(); $('option[value="' + $(this).val() + '"]', this).attr('selected', 'selected'); });
      $('#' + form2 + ' :input').not(':submit').clone().hide().attr('isacopy','y').appendTo('#' + form1);
      return true;
    }
  };
</script>

And your form tags would look something like (notice the form ids passed to the function are switched):

你的表单标签看起来像(注意传递给函数的表单 id 被切换):

<form name="my_first_form" id="my_first_form" method="post" onsubmit="if (!submitter.combine('my_first_form', 'my_second_form')) { return false; }">
...
<form name="my_second_form" id="my_second_form" method="post" onsubmit="if (!submitter.combine('my_second_form', 'my_first_form')) { return false; }">

Form validation can fit in there wherever you like - it would make most sense if your validator was another function of the submitter object, or vice versa.

表单验证可以放在任何你喜欢的地方——如果你的验证器是提交者对象的另一个功能,反之亦然,这将是最有意义的。

回答by Somwang Souksavatd

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() {

            }
        });

回答by Dancrumb

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 bothforms whenever the user submits one.

虽然其他答案解决了您提出的问题,但如果您想在用户提交表单时同时发送这两个表单的内容,则可能值得考虑为什么您有 2 个单独的表单。

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.

如果您使用 2 种不同的形式在视觉上将它们分开,更好的方法可能是使用 CSS 根据需要将元素放置在屏幕上。这样,您就不会依赖 Javascript 的存在来确保正确填充表单。

回答by Sarfraz

I used below code to submit two forms' data in my website.

我使用下面的代码在我的网站上提交了两个表单的数据。

The idea is that you get the multiple forms datausing serializeand combine that data and equalize that to dataparameter of the $.ajaxfunction.

这个想法是您使用并组合该数据并将其均衡为函数的参数来获取多个表单数据serializedata$.ajax

.

.

// submits two forms simultaneously
function submit_forms(form1_id, form2_id)
{
    var frm1_name = $("#" + form1_id).attr('name');
    var frm2_name = $("#" + form2_id).attr('name');

    if (frm1_name == frm2_name)
    {
        alert('The two forms can not have the same name !!');
    }
    else
    {
        var frm1_data = $("#" + form1_id).serialize();
        var frm2_data = $("#" + form2_id).serialize();

        if (frm1_data && frm2_data)
        {
            $("#div_busy").html('<strong>Processing...</strong><br /><img id="busy" src="./images/progress_bar.gif" border="0" style="display:none;" />');
            $("#busy").fadeIn('slow');

            $.ajax(
            {
                   type: "POST",
                   url: "process_sticker_request.php",
                   data: frm1_data + "&" + frm2_data,
                   cache: false,

                   error: function()
                   {
                        $("#busy").hide('slow');
                        $("#div_busy").css({'color':'#ff0000', 'font-weight':'bold'});
                        $("#div_busy").html('Request Error!!');
                   },
                   success: function(response)
                   {
                        $("#div_busy").hide('slow');
                        $("#hdnFormsData").html(response);

                            // open popup now with retrieved data
                            window.open('', 'popup2', 'toolbars = 1, resizable=1, scrollbars=1, menubar=1');
                            document.getElementById("prt").action = 'win_sticker.php';
                            document.getElementById("prt").target = 'popup2';
                            document.getElementById("prt").submit();

                            // reset the action of the form
                            document.getElementById("prt").action = 'list_preview.php';

                   }
             });                
        }
        else
        {
            alert('Could not submit the forms !!');
        }
    }
}

回答by Glibo

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

这是用于合并两种形式的干净的 javascript 方法。我使用 Prototype 和 jQuery 在 POST 请求上测试它并且它工作正常。事情是这样的:

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

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

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

注意:'form1'是表单id,需要在<form id="form1"></form>中设置

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

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

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

注意:'form2'是表单id,需要在<form id="form2"></form>中设置

Now you have two varsand 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 concatfunction.

现在您有两个变量和两个序列化数据(数组)。您可以轻松合并它们。您的表单将具有关联。数组,当您尝试使用concat函数时可能会遇到问题。

var mergeddata = data1 + '&' + data2;

var 合并数据 = 数据 1 + '&' + 数据 2;

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

就是这个!您可以轻松地通过 ajax 调用发送它们。例如(Prototype.js):

new Ajax.Request(url, { method: 'post', parameters: mergeddata, ....

new Ajax.Request(url, { 方法: 'post', 参数: 合并数据, ....

Cheers, Kristijan

干杯,克里斯蒂安

回答by Colin

Using serializeto 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:

使用serialize组合表单并使用 ajax 提交对我有用,直到我添加了一个“导出”按钮(将数据作为 excel 文件发送)。为此,我需要做一个完整的回发。所以我最终采用了这种方法。它选择了适当的合并技术,并在此过程中修复了按钮、选择和文本区域的一些问题:

$("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;
});

回答by AbdessamadEL

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:

对于示例 obj1 和 obj2,它返回:

// Example

// 例子

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

I wish it helps

我希望它有帮助