2013-05-14 22 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

相關問題