Reputation: 1714
In the following structure:
<input type="text" class="form-control" id="price" placeholder="Price">
<input type="text" class="form-control" id="sum_amount" placeholder="Total amount">
<input type="text" class="form-control" id="sum_total" placeholder="Grand total">
<table class="table" id="tab1">
<thead>
<tr>
<th>Price</th>
<th>Amount</th>
<th>Total</th>
<th>
</th>
</tr>
</thead>
<tbody class="tableSell">
<tr>
<td>625</td>
<td>1</td>
<td>625</td>
</tr>
<tr>
<td>638</td>
<td>2.5</td>
<td>1595</td>
</tr>
<tr>
<td>640</td>
<td>4</td>
<td>2560</td>
</tr>
</tbody>
</table>
I need to calculate the subtotals of 'Amount' and 'Total' columns based on the clicked row. Example: If the second row is clicked: 'Total amount' = 3.5, 'Grand total' = 2220
I've been able to achive copying of the price to the first field
$(document).ready(function(){
$("#tab1 tr").click(function(){
$("#price").val($(this).find(':first-child').text());
});
});
but I have no idea how to develop the subtotals.
The workspace: http://jsfiddle.net/Tge9A/1/
Upvotes: 0
Views: 974
Reputation: 24885
$(document).ready(function(){
$("#tab1 tr").click(function(){
var amount = parseFloat($(this).find(':eq(1)').text());
var price = $(this).find(':first-child').text();
var total = 0;
//add one to amount and get this rows total
amount += 1;
total = amount * price;
var grandTotal = 0;
var sum_amount = 0;
//update the row
$(this).find(':eq(1)').text(amount);
$(this).find(':eq(2)').text(total);
var count = 0;
//now loop through the rows and get the totals - the count is to ignore the first row as it is table headings
$.each($('table tr'), function( i, val ) {
if (count > 0){
sum_amount += parseFloat($(val).find(':eq(1)').text());
grandTotal += parseFloat($(val).find(':eq(2)').text());
}
count ++;
});
$('#sum_amount').val(sum_amount);
$('#sum_total').val(grandTotal);
}); });
Upvotes: 2
Reputation: 652
EDITED: Fixed to parseFloat()
and added JSFiddle.
Try initializing your totals to the current ones in the row. Then loop back to all the previous rows and add those to the totals like so (this would go in your .click()
function):
var totalAmount = parseFloat($(this).children('td').eq(1).text());
var grandTotal = parseFloat($(this).children('td').eq(2).text());
$(this).prevAll('tr').each(function() {
totalAmount += parseFloat($(this).children('td').eq(1).text());
grandTotal += parseFloat($(this).children('td').eq(2).text());
});
You might also want to specify your selector for your click event to be more like:
$('#tab1 > tbody > tr')
This will prevent parse errors since the header row in your thead
section won't be selected with this.
Upvotes: 1