I'm a relative newb with jQuery but I've managed in the past to cobble together a few simple scripts. I've got a new challenge and I know I'm 'in the zone but I need some help.
I have an html page, with numerous tables in this format:
<table class="tableClass" id="tableID">
<col class="date" />
<col class="reference" />
<col class="amount" />
<thead>
<tr>
<th class="date">Date</th>
<th class="reference">Reference</th>
<th class="amount">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>01-11-09</td>
<td>text here</td>
<td>33.66</td>
</tr>
<!— [ etc., many more rows ] -->
<tr class="total">
<td colspan="2">TOTAL:</td>
<td class="amount total"></td>
</tr>
</tbody>
</table>
I'm using this bit of jQuery to add the class="amount" to the third cell:
<script type="text/javascript">
$(document).ready(function(){
$("tbody tr td:nth-child(3)").addClass("amount").append("<span>$<\/span>");
});
</script>
... which works as intended.
My objective is to have jQuery calculate in each of multiple tables the total of the 'amount' cells, and display the result in the designated cells (tr.total td.total). With help from a non-jQuerying javascripter, I've cobbled this together:
// instantiate the 'total' variable
var total = 0;
var currTotal = 0.00;
$(document).ready(function(){
$('table').each(function(){
// iterate through 3rd cell in each row in the tbody (td with an amount):
$("#tableID tbody tr td:nth-child(3)").css("color", "red").each(function() {
total += parseInt(100 * parseFloat($(this).text()));
});
currTotal = total/100;
alert('Total = $ ' + currTotal);
$(this).parent().find(".total .amount").html('<span>$<\/span>' + currTotal);
});
});
This (apparently) totals all 'amount' cells in the page, and writes it in all the 'total' cells - close but obviously I'm not correctly specifying that each total should be displayed in its parent. I'd greatly appreciate it if anyone can please straighten me out on what I'm missing, and if there's a simpler way to achieve the rest of it, I'm all ears.
Cheers, svs