Reputation: 743
I have some checkboxes with values which need sum up. When the checkboxes are checked the values get added in an array and displayed. Here is a demo link: http://jsfiddle.net/maxwellpayne/gKWmB/ However when I go to a new row it continues summing my values instead of starting afresh emptying the array on row change.The HTML code is long so please view it at the link provided.
Here is the jquery code summing them up:
var total_array = new Array();
var total_amount = 0;
$("#dailyexpense input[type=checkbox]:checked ").live('change', function() {
var check_id = $(this).attr('id');
var valu = $(this).val();
$("#tdtotals input[type=text]").each(function() {
totals_id = $(this).attr('id');
if (totals_id == check_id) {
total_array.push(valu);
total_amount = eval(total_array.join('+')).toFixed(2);
$(this).val(total_amount);
}
});
});
All help will be appreciated
PS: However is editing the code in jsfiddle and distorting everything, stop it.
Upvotes: 1
Views: 1869
Reputation: 39872
Try this:
Basically we rethink the structure. If a checkbox value changes we get its parent row. Then we find all checkboxes in that row. Finally we total them and display.
//watch checkboxes
$('tr input[type=checkbox]').change( function(){
var total = 0;
//total all sibling checkboxes
$(this).parents('tr').find('input[type=checkbox]:checked').each( function() {
total += parseInt($(this).val());
});
//display the result
$(this).parents('tr').find('input[type=text]:last').val(total);
});
Upvotes: 3