简体   繁体   English

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

[英]How to sum selected rows in table using jQuery?

There is a table 这里有张桌子

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"> |

I want to get sum of columns below "SUM row" when input value is changed. 当输入值改变时,我希望在“SUM行”下面得到列的总和。 If there is other column ex FOO BAR it shouldn't be count to sum. 如果还有其他列ex FOO BAR,则不应计入总和。

What is aproach here? 什么是aproach在这里? Dummy idea: every column has reference where it value will be summed. 虚拟的想法:每列都有参考值,它的值将被加总。

Fiddle for quick start: http://jsfiddle.net/igos/vNxzu/ 小提琴快速入门: http//jsfiddle.net/igos/vNxzu/

EDIT It should sum up till next sum row right. 编辑它应该总结到下一个总和右边。

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

It should be dynamic, so when more rows come it will automatically add more rows. 它应该是动态的,所以当更多行出现时,它会自动添加更多行。

Try 尝试

$('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);
});

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM