Merge values from two forms on submit

JqueryHtml

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

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

Solution 2 - Jquery

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

Solution 3 - Jquery

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:

<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):

<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.

Solution 4 - Jquery

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

Solution 5 - Jquery

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.

Solution 6 - Jquery

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, ...

Solution 7 - Jquery

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

The idea is that you get the multiple forms data using serialize and combine that data and equalize that to data parameter of the $.ajax function.

.

// 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 !!');
		}
	}
}

Solution 8 - Jquery

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

Solution 9 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrianView Question on Stackoverflow
Solution 1 - JquerySagiView Answer on Stackoverflow
Solution 2 - JqueryLachlan RocheView Answer on Stackoverflow
Solution 3 - JqueryiisisraelView Answer on Stackoverflow
Solution 4 - JquerySomwang SouksavatdView Answer on Stackoverflow
Solution 5 - JqueryDancrumbView Answer on Stackoverflow
Solution 6 - JqueryGliboView Answer on Stackoverflow
Solution 7 - JquerySarfrazView Answer on Stackoverflow
Solution 8 - JqueryColinView Answer on Stackoverflow
Solution 9 - Jqueryuser7153178View Answer on Stackoverflow