簡體   English   中英

如何使用jQuery對表中的選定行進行求和?

[英]How to sum selected rows in table using 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行”下面得到列的總和。 如果還有其他列ex FOO BAR,則不應計入總和。

什么是aproach在這里? 虛擬的想法:每列都有參考值,它的值將被加總。

小提琴快速入門: 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

它應該是動態的,所以當更多行出現時,它會自動添加更多行。

嘗試

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

演示: 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM