I have an object with some address information in it that I would like to append() to an HTML table.
The table starts like this:
<table class="shipping_information" border="1">
</table>
And then I put my address information into another table (line 5 here), and put that table into a <td>. I’m trying to make it so that there is a maximum number of <td>s (here 2). If it is over 2, a new <tr> will be appended.
function add_shipping_address_to_shipping_container(address_obj, shipping_container) {
var append_to_table = "";
var table = shipping_container.find('table.shipping_information');
var max_td = 2;
var formatted_address = format_address(address_obj); //returns a table with the address
//are there any rows in the table
var is_tr = table.find('tr.shipping_address_container_table').length;
if (!is_tr) {
//no tr so append tr and td
//colspan should be max_td
append_to_table = "<tr class='add_container'><td class='add_container'>" + formatted_address +"</td></tr>"
} else {
//there is a tr
var last_tr = table.find('tr.add_container:last');
//number of tds in the last row
var num_td = last_tr.find('td.add_container').length;
if (num_td >= max_td) {
append_to_table = "<tr class='add_container'><td class='add_container'>" + formatted_address + "</td></tr>";
} else {
append_to_table = "<td class='add_container'>" + formatted_address + "</td>";
}
}
table.append(append_to_table);
}
However, the <td>s aren’t appending as I would imagine. It makes a new <tr> each time. when I print the variable append_to_table to the console, it looks right. <tr><td></td></tr> when there should be, and just <td></td> when that should be the case. Is jquery or chrome automatically appending a new <tbody> each time or something?
When you are checking for a new row, you are searching for a class
shipping_address_container_tablebut when you are creating the new row. You are only adding a tr with classadd_container.Your current code isn’t doing anything except the first portion (
!is_tralways ==true). That’s probably your problem.Also, I moved the append for existing
trelements to thetrinstead of thetableto make sure jquery doesn’t automatically wrap thetdin a newtr.This worked for me: