I've a html table, generated by code, of many rows and column. Some of this TD has a ON class to style it differently.
The structure of table has an header, a body, and a footer row.
I'd like to sum the quantity of all the TD with class 'ON' in each column and put the result on last row (footer) in each column.
How can I do it? (the rows and column are not a 'fixed matrix', so I don't know in advance how many rows and columns has the table)
Example table:
data | id_1 | id_2 | id_3 | ...
2012-06-20 | "ON" | | | ...
2012-06-21 | "ON" | | | ...
2012-06-22 | "ON" | "ON" | | ...
2012-06-23 | "ON" | | "ON" | ...
2012-06-24 | "ON" | "ON" | | ...
tot | 5 | 2 | 1 | ...
UPDATE: mixing solutions of CRANIO and ALNITAK this is the result:
var a = [];
$('td').each(function() {
var n = $(this).index();
if($(this).hasClass('on')){
a[n] = a[n] ? a[n] + 1 : 1;
}else{
a[n] = a[n] ? a[n] : 0;
}
});
var t = $('<tr>').appendTo('#tableID > tfoot');
$.each(a, function(i, n) {
t.append($('<td>', { text: i === 0 ? 'total' : n }));
});
In this way you add ZEROS (or empty space ---> a[n] = a[n] ? a[n] : ''; <--- to columns without TD.on and resolve little bug if there are some empty cols on the end of table (in the elegant solution of alnitak the TD on last row were not added)
P.S. useful also to create different total rows, on different TD.class, appending more TR based upon different class.