I have this table:
<table id="total" border="1" width="100%">
<tbody>
<tr>
<td>Total duration time</td>
<td class="total_duration_time"></td>
</tr>
</tbody>
</table>
<table id="data" border="1" width="100%">
<tbody>
<tr>
<td>Anna</td>
<td>318</td><td class="duration_time">00:00:50</td>
<td>62700</td>
</tr>
<tr>
<td>Bob</td>
<td>318</td>
<td class="duration_time">00:00:27</td>
<td>62703</td>
</tr>
<tr>
<td>Mike</td>
<td>318</td>
<td class="duration_time">00:00:36</td>
<td>88455233284</td>
</tr>
</tbody>
</table>
I need to calculate the sum of the column with class duration_time and print result in to column with class total_duration_time.
How to do this on JavaScript or jQuery?
I tried to use the code from this example http://jsfiddle.net/unKDk/13/, but it does not calculate the amount of time if instead of numbers substitute a value of type 00:00:00.
The easiest way is to work with seconds. I mean, you can convert each duration to seconds, make the total and then show where you need using another function that converts the seconds to hh-mm-ss format.
You can check how it looks and it works here
Note : the function toHHMMSS() is taken form here
Here's a full example with carry (assuming the format is HOURS:MINUTES:SECONDS), maybe not the best solution for computation:
HTML
<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">00:55:23</td>
<td class="rowDataSd">00:55:23</td>
<td class="rowDataSd">00:55:23</td>
</tr>
<tr>
<td class="rowDataSd">00:55:23</td>
<td class="rowDataSd">00:55:23</td>
<td class="rowDataSd">00:55:23</td>
</tr>
<tr>
<td class="rowDataSd">00:55:23</td>
<td class="rowDataSd">00:55:23</td>
<td class="rowDataSd">00:55:22</td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</table>
JS
var totals = [[0,0,0], [0,0,0], [0,0,0]];
$(document).ready(function () {
var $dataRows = $("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function () {
$(this).find('.rowDataSd').each(function (i) {
time = $(this).html().split(":")
totals[i][2] += parseInt(time[2]);
if(totals[i][2] > 60)
{
totals[i][2] %= 60;
totals[i][1] += parseInt(time[1]) + 1;
}
else
totals[i][1] += parseInt(time[1]);
if(totals[i][1] > 60)
{
totals[i][1] %= 60;
totals[i][0] += parseInt(time[0]) + 1;
}
else
totals[i][0] += parseInt(time[0]);
});
});
$("#sum_table td.totalCol").each(function (i) {
console.log(totals[i]);
$(this).html("total:" + totals[i][0] + ":" + totals[i][1] + ":" + totals[i][2]);
});
});
http://jsfiddle.net/unKDk/192/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With