Reputation: 345
I have a span where on initial load the sum is displayed of all the checkboxes (all checked). When unchecking one of the checkbox, the value within that checkbox should be decreased from the sum. I have tried this, but in stead of decreasing that value, when unchecking it is doubling the value. E.g. of the checked values: 42,13,100 = 155, unchecking 42 should give 113 but is resulting in 310.
Demo: http://jsfiddle.net/M7ghD/6/
var sum = 0;
$('.numbers').each(function() {
sum += parseInt($.text(this), 10);
});
$(".total").text(sum);
$('.checkbox').change(function () {
//assign
var sumChange = 0;
//for each checked checkbox
$('.checkbox:checked').each(function () {
$('.numbers').each(function() {
sumChange += parseInt($.text(this), 10);
});
});
$(".total").text(sumChange);
});
Upvotes: 2
Views: 211
Reputation: 207901
I'd change your change function to:
$('.checkbox').change(function () {
//assign
var sumChange = 0;
//for each checked checkbox
$('.checkbox:checked').each(function () {
sumChange += parseInt($(this).parent().text(), 10);
});
$(".total").text(sumChange);
});
Upvotes: 5