Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  186] [ 5]  / answers: 1 / hits: 24645  / 11 Years ago, thu, january 30, 2014, 12:00:00

Sum table cell



<table>
<tr>
<td><input type=text></td>
<td><input class=price type=text value=100></td>
<td><input class=quantity type=text value=2></td>
<td><input type=text></td>
</tr>
<tr>
<td><input type=text></td>
<td><input class=price type=text value=100></td>
<td><input class=quantity type=text value=5></td>
<td><input type=text></td>
</tr>
<tfoot>
<tr class=summary>
<td>Total:</td>
<td id=total_price></td>
<td id=total_quantity></td>
<td class=second></td>
<td class=third></td>
</tr>
</tfoot>
</table>


<script>
$(document).ready(function() {
var sum = 0;
var quantity = 0;
$('.price').each(function() {
sum += (parseInt($('.price').val()) * parseInt($('.price').val()));
quantity += parseInt($('.quantity').val();
});

$('#total_price').html(sum);
$('#total_quantity').html(quantity);
})
</script>


Output must be: Total sum: 700; Total quantity: 7


More From » jquery

 Answers
23

Change $('.price') to $(this), to refer the element inside the callback.



$(document).ready(function() {
var sum = 0;
var quantity = 0;
$('.price').each(function() {
var price = $(this);
var q = price.closest('tr').find('.quantity').val();
sum += parseInt(price.val()) * parseInt(q);
quantity += parseInt(q);
});

$('#total_price').html(sum);
$('#total_quantity').html(quantity);
});


Fiddle Demo


[#72840] Wednesday, January 29, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karleel

Total Points: 309
Total Questions: 79
Total Answers: 86

Location: Monaco
Member since Sun, Jan 16, 2022
2 Years ago
;