0

I'm shifting form #cart_form from right column to left column after a button is hit.

And the code for that is:

$('#left_col').html($('#cart_form').html());

But I cannot submit it. I wondered if the code above properly copied all tags, right from <form> to </form>

I checked if form element exists, like this:

if ($('form').length == 0) {
   alert("no");
}

And it doesn't alert 'no' meaning it exist. The markup for my form is,

<form action="#" method="POST" id="cart_form">
<table class='header_tbl' style="background:none !important;">
<thead>
    <tr>
        <th>Item Name</th>
        <th>Unit Price</th>
        <th>Qty</th>
        <th>Amount(RM)</th>
        <th></th>
    </tr>
</thead>
.........................
CONTENT APPENDED BY JQueRY
........................

This button initiates the submission:

<input type='submit' name='submit' id='receipt' onclick='print_me()' value='PRINT RECEIPT'/>

And this is how it submit if cart is not empty.

function print_me(){
     var ele = $(".header_tbl tbody tr").children().length;

     if(ele > 0)
     {
$("#cart_form").submit(function(){
                var data = {
                  "action": "test"
                };
                data = $(this).serialize() + "&" + $.param(data);
                $.ajax({
                  type: "POST",
                  dataType: "json",
                  url: "submit_cart.php",
                  data: data,
                  success: function(data) {
                 alert(data);
                   }
                  });
               });


}else
     {
       alert("Your cart is empty.");
     }
}
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
112233
  • 2,406
  • 3
  • 38
  • 88
  • Moving elements this way you loose event handlers. Check this question and answer - http://stackoverflow.com/questions/10716986/swap-2-html-elements-and-preserve-event-listeners-on-them – Nikolay Ermakov Jan 15 '16 at 04:41
  • He is not loosing his event handler because the onclick event is used directly on the button – Pierre-Luc Bolduc Jan 15 '16 at 05:01
  • Agree. He is copying only inner html. That is why no form tag there. He should grab outer html: $('#cart_form')[0].outerHTML – Nikolay Ermakov Jan 15 '16 at 05:10

2 Answers2

1

$("#yourform").html() is copying what is inside your form tag without your form tag.

Try to put your form into a div

<div id="divID">
<form action="#" method="POST" id="cart_form">
<table class='header_tbl' style="background:none !important;">
<thead>
    <tr>
        <th>Item Name</th>
        <th>Unit Price</th>
        <th>Qty</th>
        <th>Amount(RM)</th>
        <th></th>
    </tr>
</thead>
</form>
</div>

and then do that :

$('#left_col').html( $("#divID").html() );
Pierre-Luc Bolduc
  • 485
  • 1
  • 5
  • 18
1

Try $('#left_col').html( $('#cart_form')[0].outerHTML )

Nikolay Ermakov
  • 5,031
  • 2
  • 11
  • 18