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

时间:2013-05-14 11:12:57

标签: javascript 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

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

1 个答案:

答案 0 :(得分: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