2013-03-12 83 views
0

当我单击复选框删除表格行时,我希望我的计算更新总计。我在类似的情况下通过简单地将计算总和函数添加到移除行事件来完成此操作,但似乎无法在这种情况下使用它。代码:删除行时更新列计算

//Remove Table Row 
$(document).on('click', 'input.removeItem', function(){ 
$(this).closest('tr').remove(); 
calculateSum(); 
calculateTotal(); 
}); 

// Sum Amt Collected  
$(document).on('keyup', 'input.amtcollected', calculateSum); 
function calculateSum() { 
var sum = 0; 
var currentTable = $(this).closest('table').attr('id'); 
$('#' + currentTable + ' input.amtcollected').each(function() { 
//add only if the value is number 
if(!isNaN(this.value) && this.value.length!=0) { 
    sum += parseFloat(this.value); 
} 
}); 
//.toFixed() method will roundoff the final sum to 2 decimal places 
$('#' + currentTable + ' input.sumamtcollected').val(sum.toFixed(2)); 
} 

// Daily Collection Total 
$(document).on('keyup', 'input.amtcollected', calculateTotal); 
function calculateTotal() { 
var sum = 0; 
$('input.sumamtcollected').each(function() { 
//add only if the value is number 
if(!isNaN(this.value) && this.value.length!=0) { 
    sum += parseFloat(this.value); 
} 
}); 
//.toFixed() method will roundoff the final sum to 2 decimal places 
$('input.dailycollectionstotal').val(sum.toFixed(2)); 
} 

我在这里创造一个小提琴:http://jsfiddle.net/tmac187/pQ8WD/

我把警报calculateTotal后();并弹出警报。不知道为什么它不起作用。 jslint没有显示任何我可以看到的注意事项。我试过萤火虫,但我还是相当新的,所以不是100%确定我在找什么...

感谢您的帮助!

回答

1

一个小错误

//Remove Invoice Line 
$(document).on('click', 'input.removeItem', function() { 
    var currentTable = $(this).closest('table').attr('id'); 
    $(this).closest('tr').remove(); 
    calculateTableSum(currentTable); 
    calculateTotal(); 
}); 

.... 

function calculateSum() { 
    var currentTable = $(this).closest('table').attr('id'); 
    calculateTableSum(currentTable); 
} 

function calculateTableSum(currentTable) { 
    var sum = 0; 
    $('#' + currentTable + ' input.amtcollected').each(function() { 
     //add only if the value is number 
     if(!isNaN(this.value) && this.value.length!=0) { 
      sum += parseFloat(this.value); 
     } 
    }); 
    //.toFixed() method will roundoff the final sum to 2 decimal places 
    $('#' + currentTable + ' input.sumamtcollected').val(sum.toFixed(2)); 
} 

演示:Fiddle

var currentTable = $(this).closest('table').attr('id');calculateSum是越野车,当你从remove处理器从那时起this指向window对象,而不是已删除的项目调用。

+0

完全是我在找的!感谢您的帮助Arun! – Tmac 2013-03-12 13:09:27