Question

I'm having below html structure,

<table id="myTable">
  <tbody>
    <tr>
        <td>...</rd>
        <td>...</rd>
    </tr>
  </tbody>
</table>

I'm trying to include below before table ends,

<tfoot>
   <tr>
     <th>...</th>
     <th>...</th>
   </tr>
</tfoot>

One logic here is, i need to include only 2 two columns (2 "th" tags), because top i have only two columns.

So is there any way to count and append equal table columns dymanically?

Was it helpful?

Solution

you can use length to get the number of columns. Here is my answer variant

var noOfColumns = $('#myTable tbody tr td').length;
$('<tfoot><tr></tr></tfoot>').appendTo('#myTable');
for(var i = 1; i <= noOfColumns; i++){
  $('#myTable tfoot tr').append('th');
}

OTHER TIPS

There are many ways to do it

$html = '<tfoot>
   <tr>
     <th>...</th>
     <th>...</th>
   </tr>
</tfoot>';
Try using $('#myTable').append($html);

demo

use .append()

$("#myTable").append("<tfoot><tr><th>foot1</th><th>footer2</th></tr></tfoot>");

You need to use jQ for this.

to count child elements of your tr tag u should use a line like this

$count = $("#myTable tbody tr td").length;

BUT THIS CODE WILL GIVE YOU THE COUNT OF ALL THE TD ELEMENTS IN THE TABLE i mean if you have 2 tr elements containing 2 td each the selector length above will return 4 instead of 2

You can fix this by giving your tr elements an id then selecting them and counting their childs or td elements inside.

and for appending your footer u could use this.

$("#myTable").append("<tfoot><tr>");
for(i=1,i<$count,i++){
     $("#myTable tfoot").append("<th>...</th>")
}
$("#myTable").append("</tr></tfoot>");

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top