Reputation: 10484
I have a page with dynamically generated tables per date. Each date has a column which displays the amount paid per product. E.g.,
<table class="table">
<thead>
<tr>
<th>
<b>Product</b>
</th>
<th>
<b>Amount</b>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Kroket
</td>
<td>
€ 5.00 <!-- Dynamically generated -->
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total:</td>
<td class="total"></td>
</tr>
</tfoot>
</table>
So on this page are a list of tables sorted by date for which I want to display a total amount.
I want this total amount displayed in the td element with class="total". To do this I am trying to use the following JQuery function:
function updateTotalOfTotals() {
$(".table").each(function () {
var totalSum = 0;
var $dataRow = $('table tbody tr');
$dataRow.each(function () {
// In reality I have some more td elements and the amounts
// are in the 4th column.
$(this).find('td:nth-child(4)').each(function (i) {
totalSum += parseFloat($(this).text().replace("€", ""));
});
});
var twoPlacedFloatTotalSum = parseFloat(totalSum).toFixed(2);
$(".total").each(function (i) {
$(this).html(twoPlacedFloatTotalSum);
});
});
}
A similar function does work when I have only one table. But here I cannot get it to work since it displays the total of ALL tables in every table. I am no expert in JavaScript/JQuery by any means and would be very grateful if someone can provide me with more insight.
Upvotes: 0
Views: 896
Reputation: 388316
function updateTotalOfTotals() {
$(".table").each(function () {
var totalSum = 0;
//target only the trs from current table
var $dataRow = $(this).find('tbody tr');
$dataRow.each(function () {
$(this).find('td:nth-child(2)').each(function (i) {
totalSum += parseFloat($(this).text().replace("€", ""));
});
});
var twoPlacedFloatTotalSum = parseFloat(totalSum).toFixed(2);
//target only the total from current table
$(this).find(".total").html(twoPlacedFloatTotalSum);
});
}
Demo: Fiddle
Upvotes: 3