2013-05-14 24 views
0

有一个表如何使用jQuery对表中的选定行进行求和?

SUM | <input type="text"> | <input type="text"> | 
    | <input type="text"> | <input type="text"> | 
    | <input type="text"> | <input type="text"> | 
SUM | <input type="text"> | <input type="text"> | 
    | <input type="text"> | <input type="text"> | 
FOO | <input type="text"> | <input type="text"> | 
BAR | <input type="text"> | <input type="text"> | 

我想,当输入值发生改变,将会在下面“SUM行”栏目的总和。 如果有其他列FOO BAR它不应该算作总和。

这是什么意思?虚拟的想法:每一列都有参考,它的价值将被汇总。

捣鼓快速启动: http://jsfiddle.net/igos/vNxzu/

编辑 应该总结到明年总和排右。

row 0 col 0 = row 1 col 0 + row 2 col 0 
row 0 col 1 = row 1 col 1 + row 2 col 1 
row 3 col 0 = row 4 col 0 
row 3 col 1 = row 4 col 1 

它应该是动态的,所以当更多的行来时,它会自动添加更多的行。

+0

应该总结到明年之行吧? – 2013-05-14 11:24:06

+0

是的。那就对了。 – 2013-05-14 11:25:02

+0

为什么不只是添加一个类(例如'class =“sumCell”'),只需使用jQuery来选择这些单元格并在值更改时对值进行求和? – 2013-05-14 11:25:34

回答

2

尝试

$('tr.sumToUp input').change(function(){ 
    var $this = $(this), $row = $this.closest('tr'), $sum = $row.prevAll('.sumToMe').first(), $rows = $sum.nextUntil('.sumToMe', '.sumToUp'), index = $this.closest('td').index(); 

    var sum = 0; 
    $rows.each(function(){ 
     var val = $(this).find('td').eq(index).find('input').val(); 
     sum += (+val); 
    }) 
    $sum.find('td').eq(index).find('input').val(sum); 
}); 

演示:Fiddle

相关问题