2

I am creating a add to cart program and need to add product with its attribute(colors, size) to the cart and for that I need to submit both the forms together. I am not sure where am I going wrong here I have created the scripts but it submits only the first form selected for submit() using jquery but not the other form.

Given below is my code with Snippet and this is the JSFIDDLE

$(document).ready(function (){
    $('#cart').click(function (e1) {
    var $form = $('#masterform');
    var $formcolor = $('#colorform');
    var $checkbox = $('.roomselect');
    var $checkboxcolor = $('.colorselect');
    if (!$checkbox.is(':checked'))
    {
        $('#tipdivcontent').css("display", "block");
        $("#tipdivcontent").delay(4000).hide(200);
        e.preventDefault();
    }
    else
    {
        if (!$checkboxcolor.is(':checked')) {
            $('#tipdivcontentcolor').css("display", "block");
            $("#tipdivcontentcolor").delay(4000).hide(200);
            e.preventDefault();
        } else {
            $form.submit();
            $formcolor.submit();
        }
    }
    });
});
#tipdivcontent
{
    border:1px solid black;
    margin-top:0px;
    background-color:white;
    height:50px;
    width:102px;
    display:none;
    position:relative;
    background-color:red;
    color:yellow;
    font-weight:bold;
}
#tipdivcontentcolor
{
    border:1px solid black;
    margin-top:0px;
    background-color:white;
    height:18px;
    width:292px;
    display:none;
    position:absolute;
    background-color:red;
    color:yellow;
    font-weight:bold;
}
<form action="" method="POST" id="masterform">
    <table border="1" cellspacing="0">
        <tr>
            <th colspan="4">Sizes</th>
        </tr>
        <tr>
            <td>
                <label for="2.2">2.2</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.2" name="size" value="twopointtwo">
            </td>
            <td>
                <label for="2.4">2.4</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.4" name="size" value="twopointfour">
            </td>
        </tr>
        <tr>
            <td>
                <label for="2.6">2.6</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.6" name="size" value="twopointsix">
            </td>
            <td>
                <label for="2.8">2.8</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.8" name="size" value="twopointeight">
            </td>
        </tr>
        <tr>
            <td colspan="3" align="center">
                <label for="2.10">2.10</label>
            </td>
            <td>
                <input class="roomselect" type="radio" id="2.10" name="size" value="twopointten">
            </td>
        </tr>
    </table>
</form>
<div id="tipdivcontent">Please Select Size.</div>
<input type="submit" value="To Cart" class="cartorcheckoutbutton" id="cart">
<form action="" method="POST" id="masterform">
    <table border="1" cellpadding="2">
        <tr>
            <th colspan="8">COLORS</th>
        </tr>
        <tr>
            <th title='White' style='background-color:white;' height='15' width='20'>
                <input type='radio' name='color' class="colorselect" value='white'>
            </th>
            <th title='Red' style='background-color:red;' height='15' width='20'>
                <input type='radio' name='color' class="colorselect" value='red'>
            </th>
            <th title='Green' style='background-color:green;' height='15' width='20'>
                <input type='radio' name='color' class="colorselect" value='green'>
            </th>
            <th title='Blue' style='background-color:blue;' height='15' width='20'>
                <input type='radio' name='color' class="colorselect" value='blue'>
            </th>
        </tr>
    </table>
</form>
<div id="tipdivcontentcolor">Please Select Color.</div>
Hardik Sisodia
  • 615
  • 3
  • 14
  • 37
  • why u dont use only one form?? – Vanojx1 Jul 20 '15 at 10:12
  • @Vanojx1 I can't use one form because my cart button, size table and colour table all are located at different places and they have different css customization too so I can't use single form. – Hardik Sisodia Jul 20 '15 at 10:14
  • http://stackoverflow.com/questions/8563299/submit-multiple-forms-with-one-submit-button This one has a solution where the forms are submitted by ajax request. Submit the second form in the success of the first ajax call. – Yasitha Jul 20 '15 at 10:22

5 Answers5

1

You could try assigning the color inputs from the secondary form to your 'master' form. Simply using <input form='formID' ...> on any input would assign that input to the other form regardless of where it is on the page.

// When the 'master' form is submitted...
$("#masterForm").on("submit", function(e) {
  "use strict";
  // Stop the default action
  e.preventDefault();
  
  if ($("input[type='radio']:checked").length === 0) {
    alert("You must check at least one color option.");
    return false;
  }
  
  // *for logging*
  // write the contents of the submitted data
  $("p").html("submitted data: " + $(this).serialize());
  console.log("submitted data: " + $(this).serialize());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="masterForm">
  <input name="someField" type="text" value="test value">
</form>

<form id="anotherForm">
  <label>
    <input name="color" type="radio" value="blue" form="masterForm">Blue
  </label>
  <label>
    <input name="color" type="radio" value="red" form="masterForm">Red
  </label>
</form>

<!-- Submit button outside of the form -->
  <button type="submit" form="masterForm">Submit</button>

<p></p>

If the above option (and attached snippet) wouldn't work for you, try appending your formData with the relevant fields. Something like this (untested):

// When the 'master' form is submitted...
  $("#masterForm").on("submit", function(e) {
  "use strict";
  // Stop the default action
  e.preventDefault();

  var submissionData = $(this).serialize();
  submissionData += "&color=" + $("#slaveForm").find("input[name='color']:checked").val()

  // do stuff ...
});
kneeki
  • 2,444
  • 4
  • 17
  • 27
  • I need to submit the form only if both forms have entered value size and color should have atleast one tick for submitting the form and my submit button is not inside the form so need to submit it from outside the form. – Hardik Sisodia Aug 30 '15 at 07:06
  • See edited code above. By moving the submit button from the form and applying the `form='...'` tags you are able to achieve the same result. Regarding the color requirement, simply putting a check on the radio inputs and alerting the user if nothing is checked works. – kneeki Aug 31 '15 at 23:48
0

A form is a set of data to be sent via a POST request (or GET). What you are asking for makes no sense. If it is possible then you still shouldn't do it. Whatever HTML and CSS issues are making you split the form then I recommend you put that as your actual problem here.

HenryTK
  • 1,287
  • 8
  • 11
0

Submitting a form, unless it has a target attribute pointing to a frame or other window, will cause an HTTP request for a new page to be made.

Submitting two forms at the same time would be like following two links at the same time. It can't be done.

You need to either:

  • Refactor your code so it uses a single form. This would almost certainly make the most sense.
  • Add a pair of frames to the page and submit each form to a different one.
  • Collect the data for the first form with JavaScript, sent it to the server using Ajax, then (after you get the response back) submit the second form.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

If you want to send multiple form as a single one i can suggest to use formData object (documentation https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects )

var formData = new FormData();

formData.append("size", $('input[name=size]:checked').val());

formData.append("color", $('input[name=color]:checked').val());

var request = new XMLHttpRequest();  
request.open("POST", "yourformtarget");
request.send(formData);
Vanojx1
  • 5,574
  • 2
  • 23
  • 37
0

A possible solution with javascript: you can add an attribute to locate all fields, and send the form by ajax:

<div id='masterform'>
    <input name='field_1' data-field-of='form1'>
    ...
</div>
...
<div id='colorform'>
    <input name='field_23' data-field-of='form1'>
     ...
</div>

The code in javascript can be something like this:

$(document).ready(function (){      

    $('#cart').click(function (e1) {
        var data = $('[data-field-of=form1]').serialize();
        $.ajax({
            url: "post/url",
            data: data,
            type: "POST",
            success: function(response){ /* handle success */ },
            error: function(){ /* handle error */ }
        });
    });
});
Carlos Gant
  • 731
  • 6
  • 15