jQuery highlight row within specific time - javascript

I am trying to highlight a row, when it's within a specific time range.
So actually let's say its 10:00:00 and i need to mark the row, if the time is between the start end the enddate-row.
the table:
<table class="table table-striped" id="timeTable">
<thead>
<th>Title</th>
<th>Start</th>
<th>End</th>
<th>Channel</th>
</thead>
<tbody>
<tr>
<td>Title 1</td>
<td class="dateRowStart">2016-08-10 09:00:00+02</td>
<td class="dateRowEnd">2016-08-10 11:00:00+02</td>
<td>Channel 1</td>
</tr>
<tr>
<td>Title 2</td>
<td class="dateRowStart">2016-08-10 09:30:00+02</td>
<td class="dateRowEnd">2016-08-10 12:00:00+02</td>
<td>Channel 3</td>
</tr>
<tr>
<td>Title 4</td>
<td class="dateRowStart">2016-08-10 13:00:00+02</td>
<td class="dateRowEnd">2016-08-10 15:00:00+02</td>
<td>Channel 4</td>
</tr>
</tbody>
</table>
The dateformat is the output of my postgresql db. It would be great if I could show them in our local time format (10.08.2016 - 14:15:12) but thats not my main issue here.
my (only half complete) js code to highlight:
<script>
$('#timeTable .dateRowStart').each(function () {
var dtTd = new Date($(this).html());
var dtNew = new Date();
if (dtNew.getTime() < dtTd.getTime()) {
$(this).parent('tr').addClass('highlight');
}
});
</script>
I don't know how to include dateRowEnd to check, if the date is still between the start/end-time. If I'm using two identical time/dates with dateformat eg. "08/10/2016 10:05:00", I'm only getting one row marked., that's the other annoying thing.
Thank you!

You could add a class to the <tr> tags themselves and then do:
HTML:
<tbody>
<tr class="dateRow">
<td>Title 1</td>
<td class="dateRowStart">2016-08-10 09:00:00+02</td>
<td class="dateRowEnd">2016-08-10 11:00:00+02</td>
<td>Channel 1</td>
</tr>
...
</tbody>
jQuery:
$('#timeTable').find('.dateRow').each(function () {
var dtStart = new Date($(this).find(".dateRowStart").text());
var dtEnd = new Date($(this).find(".dateRowEnd").text());
var dtNew = new Date();
if (dtNew >= dtStart && dtNew <= dtEnd) {
$(this).addClass('highlight');
}
});
Note you only have to use .getTime() if you're doing ==, !=, ===, and !== on Date objects as seen here.
Edit: As #MarkSchultheiss suggested, separating $('#timeTable .dateRow') into $('#timeTable').find('.dateRow') has a slight efficiency boost.

With moment.js you can do --
$('#timeTable .dateRow').each(function () {
var startTime = $(this).closest("tr").find(".dateRowStart") .text();
var endTime = $(this).closest("tr").find(".dateRowEnd").text();
if (moment().isBetween(startTime, endTime)) {
$(this).addClass('highlight');
}
});
codepen -- http://codepen.io/anon/pen/OXAEAv
You can also change the date format with moment('orig date').format('MM/DD/YY HH:mm:ss')

Check this snippet:
$(function() {
$('#timeTable .dateRowStart').each(function() {
var dtTdStart = new Date($(this).text());
var dtTdEnd = new Date($($(this).siblings('.dateRowEnd')).text());
var dtNew = new Date();
if (dtNew > dtTdStart && dtNew < dtTdEnd) {
$(this).parent('tr').addClass('highlight');
}
else{
$(this).parent('tr').removeClass('highlight');
}
});
});
.highlight {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped" id="timeTable">
<thead>
<th>Title</th>
<th>Start</th>
<th>End</th>
<th>Channel</th>
</thead>
<tbody>
<tr>
<td>Title 1</td>
<td class="dateRowStart">2016-08-11 17:00:00+02</td>
<td class="dateRowEnd">2016-08-11 19:00:00+02</td>
<td>Channel 1</td>
</tr>
<tr class="highlight">
<td>Title 2</td>
<td class="dateRowStart">2016-08-11 17:30:00+02</td>
<td class="dateRowEnd">2016-08-11 18:00:00+02</td>
<td>Channel 3</td>
</tr>
<tr>
<td>Title 4</td>
<td class="dateRowStart">2016-08-11 13:00:00+02</td>
<td class="dateRowEnd">2016-08-11 15:00:00+02</td>
<td>Channel 4</td>
</tr>
</tbody>

Related

Javascript grab the data from the table in the HTML and build an array of objects that contains the table data

I have an HTML table and I need to define a function that should grab the data from the table and build an array of objects that contains table data. Outside the function I have to declare a variable and assign the returned value from the function.
Thanks in advance.
HTML
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
JS
function buildTableData() {
let tbody = document.getElementsByTagName("tbody")[0];
let rows = tbody.children;
let people = [];
for (let row of rows) {
let person = {};
let cells = row.children;
person.rating = cells[0].textContent;
person.review = cells[1].textContent;
person.favoriteFood = cells[2].textContent;
people.push(person);
return people;
}
let data = people;
console.log(data);
}
You can get all the elements by using querySelectorAll('td'). Then use map to to get only the text of it and return this.
function buildTableData() {
const elements = [...document.querySelectorAll('td')];
return elements.map(x => {
return {content : x.innerHTML}
});
}
console.log(buildTableData());
<body>
<h2>Product reviews</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/7.3.1/acorn.js" integrity="sha512-4GRq4mhgV43mQBgKMBRG9GbneAGisNSqz6DSgiBYsYRTjq2ggGt29Dk5thHHJu38Er7wByX/EZoG+0OcxI5upg==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn-walk/7.2.0/walk.js" integrity="sha512-j5XDYQOKluxz1i4c7YMMXvjLLw38YFu12kKGYlr2+w/XZLV5Vg2R/VUbhN//K/V6LPKuoOA4pfcPXB5NgV7Gwg==" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
You can try using querySelectorAll() and map() like the following way:
function buildTableData() {
let rows = document.querySelectorAll('tbody tr');
let data = Array.from(rows).map(function(tr){
return {
rating: tr.querySelectorAll('td:nth-child(1)')[0].textContent,
review: tr.querySelectorAll('td:nth-child(2)')[0].textContent,
favoriteFood: tr.querySelectorAll('td:nth-child(3)')[0].textContent
};
});
console.log(data);
}
buildTableData();
<h2>Product reviews</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
You want a loop, and each review to be an object that is appended to an array of reviews is what I'm assuming
var reviews = [];
var tbody = document.querySelectorAll("tbody")[0];
var TRs = tbody.querySelectorAll("tr");
for (var a = 0; a < TRs.length; a++) {
var TDs = TRs[a].querySelectorAll("td");
var review = {
name: "",
rating: "",
review: ""
};
//These assume the order of your table columns don't change
review.name = TDs[0].innerHTML;
review.rating = TDs[1].innerHTML;
review.review = TDs[2].innerHTML;
reviews.push(review);
}
Your reviews array should have everything in there just as you wanted. I assumed the third column was "review" instead of "favorite food"

merging <td> rows in one column of html table

I have a requirement, if i have same data in column1 of 's with same id then i need to merge those cells and show their respective values in column2.
i.e., in fiddle http://jsfiddle.net/7t9qkLc0/12/ the key column have 3rows with data 1 as row value with same id and has corresponding different values in Value column i.e., AA,BB,CC. I want to merge the 3 rows in key Column and display data 1 only once and show their corresponding values in separate rows in value column.
Similarly for data4 and data5 the values are same i.e.,FF and keys are different, i want to merge last 2 rows in Value column and dispaly FF only one time and show corresponding keys in key column. All data i'm getting would be the dynamic data. Please suggest.
Please find the fiddle http://jsfiddle.net/7t9qkLc0/12/
Sample html code:
<table width="300px" height="150px" border="1">
<tr><th>Key</th><th>Value</th></tr>
<tr>
<td id="1">data 1</td>
<td id="aa">AA</td>
</tr>
<tr>
<td id="1">data 1</td>
<td id="bb">BB</td>
</tr>
<tr>
<td id="1">data 1</td>
<td id="cc">CC</td>
</tr>
<tr>
<td id="2">data 2</td>
<td id="dd">DD</td>
</tr>
<tr>
<td id="2">data 2</td>
<td id="ee">EE</td>
</tr>
<tr>
<td id="3">data 3</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="4">data 4</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="5">data 5</td>
<td id="ff">FF</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="3" style="padding-left: 0px; padding-right: 0px; padding-bottom: 0px">
</td>
</tr>
</table>
Building on tkounenis' answer using Rowspan:
One option to implement what you need would be to read all the values in your table after being populated, then use a JS object literal as a data structure to figure out what rows/columns are unique.
A JS object literal requires a unique key which you can map values to. After figuring out what rows/columns should be grouped, you can either edit the original table, or hide the original table and create a new table (I'm creating new tables in this example).
I've created an example for you to create a new table either grouped by key or grouped by value. Try to edit the examples provided to introduce both requirements.
Let me know if you need more help. Best of luck.
JSFiddle: http://jsfiddle.net/biz79/x417905v/
JS (uses jQuery):
sortByCol(0);
sortByCol(1);
function sortByCol(keyCol) {
// keyCol = 0 for first col, 1 for 2nd col
var valCol = (keyCol === 0) ? 1 : 0;
var $rows = $('#presort tr');
var dict = {};
var col1name = $('th').eq(keyCol).html();
var col2name = $('th').eq(valCol).html();
for (var i = 0; i < $rows.length; i++) {
if ($rows.eq(i).children('td').length > 0) {
var key = $rows.eq(i).children('td').eq(keyCol).html();
var val = $rows.eq(i).children('td').eq(valCol).html();
if (key in dict) {
dict[key].push(val);
} else {
dict[key] = [val];
}
}
}
redrawTable(dict,col1name,col2name);
}
function redrawTable(dict,col1name,col2name) {
var $table = $('<table>').attr("border",1);
$table.css( {"width":"300px" } );
$table.append($('<tr><th>' +col1name+ '</th><th>' +col2name+ '</th>'));
for (var prop in dict) {
for (var i = 0, len = dict[prop].length; i< len; i++) {
var $row = $('<tr>');
if ( i == 0) {
$row.append( $("<td>").attr('rowspan',len).html( prop ) );
$row.append( $("<td>").html( dict[prop][i] ) );
}
else {
$row.append( $("<td>").html( dict[prop][i] ) );
}
$table.append($row);
}
}
$('div').after($table);
}
Use the rowspan attribute like so:
<table width="300px" height="150px" border="1">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<tr>
<td id="1" rowspan="3">data 1</td>
<td id="aa">AA</td>
</tr>
<tr>
<td id="bb">BB</td>
</tr>
<tr>
<td id="cc">CC</td>
</tr>
<tr>
<td id="2" rowspan="2">data 2</td>
<td id="dd">DD</td>
</tr>
<tr>
<td id="ee">EE</td>
</tr>
<tr>
<td id="3">data 3</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="4">data 4</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="5">data 5</td>
<td id="ff">FF</td>
</tr>
</table>
http://jsfiddle.net/37b793pz/4/
Can not be used more than once the same id. For that use data-id attribute
HTML:
<table width="300px" height="150px" border="1">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valaa">AA</td>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valbb">BB</td>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valcc">CC</td>
</tr>
<tr>
<td data-id="key2">data 2</td>
<td data-id="valdd">DD</td>
</tr>
<tr>
<td data-id="key2">data 2</td>
<td data-id="valee">EE</td>
</tr>
<tr>
<td data-id="key3">data 3</td>
<td data-id="valff">FF</td>
</tr>
<tr>
<td data-id="key4">data 4</td>
<td data-id="valff">FF</td>
</tr>
<tr>
<td data-id="key5">data 5</td>
<td data-id="valff">FF</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="3" style="padding-left: 0px; padding-right: 0px; padding-bottom: 0px"></td>
</tr>
</table>
JQ:
//merge cells in key column
function mergerKey() {
// prevents the same attribute is used more than once Ip
var idA = [];
// finds all cells id column Key
$('td[data-id^="key"]').each(function () {
var id = $(this).attr('data-id');
// prevents the same attribute is used more than once IIp
if ($.inArray(id, idA) == -1) {
idA.push(id);
// finds all cells that have the same data-id attribute
var $td = $('td[data-id="' + id + '"]');
//counts the number of cells with the same data-id
var count = $td.size();
if (count > 1) {
//If there is more than one
//then merging
$td.not(":eq(0)").remove();
$td.attr('rowspan', count);
}
}
})
}
//similar logic as for mergerKey()
function mergerVal() {
var idA = [];
$('td[data-id^="val"]').each(function () {
var id = $(this).attr('data-id');
if ($.inArray(id, idA) == -1) {
idA.push(id);
var $td = $('td[data-id="' + id + '"]');
var count = $td.size();
if (count > 1) {
$td.not(":eq(0)").remove();
$td.attr('rowspan', count);
}
}
})
}
mergerKey();
mergerVal();
Use below snippet of javascript. It should work fine for what you are looking.
<script type="text/javascript">
function mergeCommonCells(table, columnIndexToMerge){
previous = null;
cellToExtend = null;
table.find("td:nth-child("+columnIndexToMerge+")").each(function(){
jthis = $(this);
content = jthis.text();
if(previous == content){
jthis.remove();
if(cellToExtend.attr("rowspan") == undefined){
cellToExtend.attr("rowspan", 2);
}
else{
currentrowspan = parseInt(cellToExtend.attr("rowspan"));
cellToExtend.attr("rowspan", currentrowspan+1);
}
}
else{
previous = content;
cellToExtend = jthis;
}
});
};
mergeCommonCells($("#tableId"), 1);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

Sorting pairs of rows with tablesorter

http://jsfiddle.net/9sKwJ/66/
tr.spacer { height: 40px; }
$.tablesorter.addWidget({
id: 'spacer',
format: function(table) {
var c = table.config,
$t = $(table),
$r = $t.find('tbody').find('tr'),
i, l, last, col, rows, spacers = [];
if (c.sortList && c.sortList[0]) {
$t.find('tr.spacer').removeClass('spacer');
col = c.sortList[0][0]; // first sorted column
rows = table.config.cache.normalized;
last = rows[0][col]; // text from first row
l = rows.length;
for (i=0; i < l; i++) {
// if text from row doesn't match last row,
// save it to add a spacer
if (rows[i][col] !== last) {
spacers.push(i-1);
last = rows[i][col];
}
}
// add spacer class to the appropriate rows
for (i=0; i<spacers.length; i++){
$r.eq(spacers[i]).addClass('spacer');
}
}
}
});
$('table').tablesorter({
widgets : ['spacer']
});
<table id="test">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
<th>Another Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Test4</td>
<td>4</td>
<td>Hello4</td>
</tr>
<tr>
<td colspan="3">Test4</td>
</tr>
<tr>
<td>Test3</td>
<td>3</td>
<td>Hello3</td>
</tr>
<tr>
<td colspan="3">Test3</td>
</tr>
<tr>
<td>Test2</td>
<td>2</td>
<td>Hello2</td>
</tr>
<tr>
<td colspan="3">Test2</td>
</tr>
<tr>
<td>Test1</td>
<td>1</td>
<td>Hello1</td>
</tr>
<tr>
<td colspan="3">Test1</td>
</tr>
</tbody>
</table>
This sorts just the way I want it if you sort it by the first column, but the other two columns don't maintain the same paired 'tr' sort im looking for.
Any help on this?
Use the expand-child class name on each duplicated row:
<tr>
<td>Test3</td>
<td>3</td>
<td>Hello3</td>
</tr>
<tr class="expand-child">
<td colspan="3">Test3</td>
</tr>
It's defined by the cssChildRow option:
$('table').tablesorter({
cssChildRow: "expand-child"
});​
Here is a demo of it in action.

How to avoid duplicate code (toggle when page loaded)?

See the code below, If you click on the sub-title row it then will hide the rows with it. It work well.
On the second sub-title row (<tr class="sub-title default-hide">) - I want this to toggle/hidden by default when the page loaded.. How to do this without writing duplicate code like below?
$(".sub-title").on("click",function() {
tr = $(this).find('span').hasClass("arrow2");
trSpan = $(this).find('span');
$(this).nextUntil(".sub-title").each(function() {
if (!$(this).hasClass('head-order')) {
$(this).toggle();
if (tr) {
trSpan.removeClass('arrow2').addClass('arrow1');
} else {
trSpan.removeClass('arrow1').addClass('arrow2');
}
}
});
});
HTML
<table border="1">
<tbody>
<tr class="head">
<td> title </td>
</tr>
<tr class="sub-title">
<td>Sub Title 1 <span class="arrow2"> </span></td>
</tr>
<tr> <td>Item 1</td> </tr>
<tr> <td>Item 2</td> </tr>
<tr> <td>Item 3</td> </tr>
<tr class="sub-title default-hide">
<td>Sub Title 2 <span class="arrow2"></span></td>
</tr>
<tr> <td>Item 4</td> </tr>
<tr> <td>Item 5</td> </tr>
<tr> <td>Item 6</td> </tr>
</tbody>
</table>
I created a jsFiddle example with the information you provided.
I edited the code a bit, using a default arrow-class and just adding the class close to it, to define the new style, which should make the code a little shorter.
$(".sub-title").on("click",function() {
var trSpan = $(this).find('span');
trSpan.toggleClass('closed');
$(this).nextUntil(".sub-title").each(function() {
if (!$(this).hasClass('head-order')) {
$(this).toggle();
}
});
});
To make the "default-hidden" - element closed on pageload, all I do is to trigger a click-event on it after binding the click-Handler.
$('.default-hide').trigger('click');
See the fiddle for a working example
Create a named function and call it a couple times:
var toggleArrow = function(el) {
tr = $(el).find('span').hasClass("arrow2");
trSpan = $(el).find('span');
$(el).nextUntil(".sub-title").each(function() {
if (!$(el).hasClass('head-order')) {
$(el).toggle();
if (tr) {
trSpan.removeClass('arrow2').addClass('arrow1');
} else {
trSpan.removeClass('arrow1').addClass('arrow2');
}
}
});
};
$(".sub-title").on("click", function(){ toggleArrow(this); });
$(".default-hide").each(function(i, el){ toggleArrow(this); });
You can trigger the click event manually for the default-hide rows.
Like this
$('.default-hide').trigger('click');

Sum total for column in jQuery

The following code isn't working. I need to sum all by column as you can see on jsfiddle. What's going wrong?
HTML
<table id="sum_table" width="300" border="1">
<tr>
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</table>
Javascript
$(document).ready(function(){
$(".rowDataSd").each(function() {
newSum.call(this);
});
});
function newSum() {
var $table = $(this).closest('table');
var total = 0;
$(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalColumn) .rowDataSd').each(function() {
total += parseInt($(this).html());
});
$table.find('.totalColumn td:nth-child('')').html(total);
}
Here is a jsffile. hope this helps
<table id="sum_table" width="300" border="1">
<tr class="titlerow">
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">5</td>
<td class="rowDataSd">3</td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</table>
<script>
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
</script>
jsFiddle with example
To achieve this, we can take full advantage of the thead and tfoot tags within the table element. With minor changes, we have the following:
HTML
<table id="sum_table" width="300" border="1">
<thead>
<tr>
<th>Apple</th>
<th>Orange</th>
<th>Watermelon</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tfoot>
<tr>
<td>Total:</td>
<td>Total:</td>
<td>Total:</td>
</tr>
</tfoot>
</table>​​​​​​​​​​​​​​​
This then allows us to target more specifically the elements we want, i.e. how many columns are there, and what is the "total" cell.
JavaScript
$(document).ready(function()
{
$('table thead th').each(function(i)
{
calculateColumn(i);
});
});
function calculateColumn(index)
{
var total = 0;
$('table tr').each(function()
{
var value = parseInt($('td', this).eq(index).text());
if (!isNaN(value))
{
total += value;
}
});
$('table tfoot td').eq(index).text('Total: ' + total);
}​
$('#sum_table tr:first td').each(function(){
var $td = $(this);
var colTotal = 0;
$('#sum_table tr:not(:first,.totalColumn)').each(function(){
colTotal += parseInt($(this).children().eq($td.index()).html(),10);
});
$('#sum_table tr.totalColumn').children().eq($td.index()).html('Total: ' + colTotal);
});
Live example: http://jsfiddle.net/unKDk/7/
An alternate way:
$(document).ready(function(){
for (i=0;i<$('#sum_table tr:eq(0) td').length;i++) {
var total = 0;
$('td.rowDataSd:eq(' + i + ')', 'tr').each(function(i) {
total = total + parseInt($(this).text());
});
$('#sum_table tr:last td').eq(i).text(total);
}
});
Example: http://jsfiddle.net/lucuma/unKDk/10/
This is easily accomplished with a little tweaking of the classes on your table:
HTML:
<table id="sum_table" width="300" border="1">
<tr>
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="total">Total:</td>
<td class="total">Total:</td>
<td class="total">Total:</td>
</tr>
</table>​
JS:
var getSum = function (colNumber) {
var sum = 0;
var selector = '.col' + colNumber;
$('#sum_table').find(selector).each(function (index, element) {
sum += parseInt($(element).text());
});
return sum;
};
$('#sum_table').find('.total').each(function (index, element) {
$(this).text('Total: ' + getSum(index + 1));
});
http://jsfiddle.net/unKDk/9/
I know this has been well answered by now, but I started working on this solution earlier before all the answers came through and wanted to go ahead and post it.
This solution works with the HTML as you posted it, and assumes 4 things: 1) the first row is the header row, 2) the last row is the totals row, 3) each row has equal columns, and 4) the columns contain integers. In this case, only the table needs to be identified.
$(document).ready(function(){
totalRows("#sum_table");
});
function totalRows(tableSelector) {
var table = $(tableSelector);
var rows = table.find("tr");
var val, totals = [];
//loop through the rows getting values in the rowDataSd columns
rows
.each(function(rIndex) {
if (rIndex > 0 && rIndex < (rows.length-1)) { //not first or last row
//loop through the columns
$(this).find("td").each(function(cIndex) {
val = parseInt($(this).html());
(totals.length>cIndex) ? totals[cIndex]+=val : totals.push(val);
});
}
})
.last().find("td").each(function(index) {
val = (totals.length>index) ? totals[index] : 0;
$(this).html( "Total: " + val );
});
}
​
​
Here you go sir! http://jsfiddle.net/47VDK/

Categories

Resources