Reputation: 1029
I have a table. Each row has a checkbox and a number in it. The number is within a span with a class.
If the checkbox is checked, I want the number to be added up with all of the other numbers in checked rows. Here is what the row looks like.
<td><input class="box" type="checkbox" name="selclips[]" value="1234"></td><td><span class="amount">45.00</span></td>
<td><input class="box" type="checkbox" name="selclips[]" value="1235"></td><td><span class="amount">65.00</span></td>
Then at the bottom I have:
<td>Total</td><td><div id="total"></div></td>
So, need some help with the JS or jquery to add up those dollar amounts with the span tags and provide a total if the checkbox is checked in that row? So, in the example above, if both boxes were checked, the script would add up 45.00 and 65.00 and put the total of 110 into the Total div. Also, if I un-check the boxes, the amount should change as well.
Thanks very much for any help anyone can give. I really appreciate it!
Upvotes: 0
Views: 3317
Reputation: 5317
var total = Array.prototype.slice.call($('input.box:checkbox:checked'), 0) // changes jQuery object to array of DOM elements
.reduce(function(a, b) { // calls reduce method
return a + Number(b.value);
}, 0);
Simple and fast.
Upvotes: 0
Reputation: 3965
Try this:
var total = 0;
$('.box').click(function(){
if($(this).prop('checked')){
total += Number($(this).closest('tr').children('td:last-child').text());
}
else{
total -= Number($(this).closest('tr').children('td:last-child').text());
}
$('#total').text(total);
});
Here is JSFIDDLE
Upvotes: 1
Reputation: 148110
You need something like
$('.box').change(function(){
var total = 0;
$('.box:checked').each(function(){
total+=parseFloat($(this).parent().next('td').find('.amount').text());
});
$('#total').text(total);
});
Upvotes: 2
Reputation: 43718
This perhaps?
var total = 0,
$totalEl = $('.total');
$('.box:checkbox').click(function () {
total += (this.checked? 1 : -1) * +this.parent('td').next().children('.amount').text();
$totalEl.text(total);
});
Upvotes: 0
Reputation: 5774
Fairly simple..
$(function(){
$( ".box" ).on( "click", function(){
console.log($(this).next().html());
var total = 0;
$('.box:checked').each(function(){
total += parseFloat($(this).next().html());
});
$("#total").text('Total is : ' + total);
});
});
This works..
Upvotes: 1