14

I have a page with several forms. I am trying to submit one of the forms (say form A) (NOT through Ajax, since I need to load the result page after the submit is processed), BUT I need another form's contents (say form B) to be submitted TOGETHER with form A, i.e. the contents of forms A + B should be submitted TOGETHER to the SAME URL, as one request, and as I said before, NOT as an Ajax request.

The submit should be by a POST request. Also, the forms contain ONLY fields that are not file upload (i.e. input, select, textarea fields).

I have seen suggestions here such as

Posting/submitting multiple forms in jQuery

or

Submitting two forms with a single button

but pay attention that these do not match my case, since the forms are submitted in different requests, and/or they are submitted through Ajax.

I was thinking of getting the contents of one of the forms by (the jQuery's) serialize(), but how do I attach that string to a form submitted by POST?

Or maybe you have other ideas how to accomplish this?

SOLUTION:

Based on the ideas of Sheepy, I wrote the following code. I am also using the answer by Pointy from the following link:

submit multiple forms to same page

//Arguments: "name"s of forms to submit.
//First argument: the form which according to its "action" all other forms will be submitted.
//Example: mergeForms("form1","form2","form3","form4")
function mergeForms() {
    var forms = [];
    $.each($.makeArray(arguments), function(index, value) {
        forms[index] = document.forms[value];
    });
    var targetForm = forms[0];
    $.each(forms, function(i, f) {
        if (i != 0) {
            $(f).find('input, select, textarea')
                .hide()
                .appendTo($(targetForm));
        }
    });
    $(targetForm).submit();
}

6 Answers 6

8

Well, you have to copy the data from form2 to form1 before the submit. Here is the basic to get you started:

$.each ( $('#form2 input, #form2 select, #form2 textarea').serializeArray(), function ( i, obj ) {
  $('<input type="hidden">').prop( obj ).appendTo( $('#form1') );
} );

This function would select inputs from form2, get their current values, then create a new hidden input for each of them and add them to form1.

Depending on your scenario you may want to check the existance of input with same name on form1 first.

Sign up to request clarification or add additional context in comments.

2 Comments

This won't include disabled inputs
Yes @Chris. Disabled inputs are not submitted normally so it's expected. jQuery's serializeArray respect the disabled property too, you'll need to enable them before the code and re-disable them after.
3

A solution to inject the data directly in the post request (and not in a sub field)

<form id="form1">
    <input ... />
    <input ... />
</form>

<form id="form2">
    <input ... />
    <input ... />
</form>

<form id="result" action="..." method="POST" onsubmit="merge(); return true;">
    <input type="submit" />
</form>


<script type="text/javascript">
    function merge() {
        $result = $("#result");
        $("#form1 input, #form2 input, #form1 select, #form2 select, #form1 textarea, #form2 textarea").each(function() {
            $result.append("<input type='hidden' name='"+$(this).attr('name')+"' value='"+$(this).val()+"' />");
        });
    }
</script>

Comments

2

You can only do one request at a time and that will reload the page unless you use AJAX. The only other option would be to create a script which concatantes the seralizations of your two forms - but at that point, why wouldn't you just use one large form..

Edit: For your combining the two forms, there is an example of this in the answer of the second link you provided.

2 Comments

Depending on the scenario, the user might want to submit only form B; or form A (in which case form B also should be submitted).
In my case, I have a 'search' form and a 'search filters' form. They are intrinsically tied together but displayed separately in the ui, but combining their values via javascript is probably an easier than trying to figure out the layout to get them both to display without disturbing any other forms the page may have...
1

form A:

<form method="post" action="next.html" onsubmit="this.formbVal.value = $('#formb').serialize(); return true;">
    <input type="hidden" name="formbVal" value="" />
    <input type="submit">
</form>

form B:

<form id="formb" method="post" action="#" onsubmit="return false;">
</form>

1 Comment

The problem with this is that I get the whole form B as a single new value. But the code on the server expects a specific list of values that matches form B (sometimes form B is submitted without any other form). I can go ahead and analyze formVal on the server and break it down but it's less elegant. Let the javascript send the form in an acceptable format.
0

I discovered that your solution will copy the form to another invissible form, but the backside is that the original forms will be cleared an such edit of the original form (eg after form validation errors) is not possible.

To solve this i tried to clone the elements before appending it to the invissible form. I edited your code like this:

//Arguments: "name"s of forms to submit.
//First argument: the form which according to its "action" all other forms will be submitted.
//Example: mergeForms("form1","form2","form3","form4")    
function mergeForms() {
        var forms = [];
        $.each($.makeArray(arguments), function(index, value) {
            forms[index] = document.forms[value];
        });
        var targetForm = forms[0];
        $.each(forms, function(i, f) {
            if (i != 0) {
                $(f).find('input, select, textarea')
                    .clone()
                    .hide()
                    .appendTo($(targetForm));
            }
        });

Unfortunatly now it doesn't copy the selected values in a select element.

Hope someone can help me to impove this script

Comments

-1

you can do some thing like this

$('#SubmitBtn).click(function () {
        $("#formId").attr("action", "http://www.YourSite.com/");
        $("#formId").attr("method", "post");
        $("#formId").attr("target","_blank");
        $('#formId').submit();
    });

this will submit the for to http://www.YourSite.com/ in a new window

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.