2014-11-24 27 views
1

我有一個從數據庫生成的表。每個字段都隱藏起來,直到從選擇下拉列表中選擇。還需要計算可見行。我有這個代碼,但它計算所有行,甚至可見。你能否建議我如何修復代碼來計算只有可見的行。JQuery - 表計算

表:

<table width="100%" border="0" id="sum_table"> 
    <tr style="color:white;background:gray;"> 
     <td>Name</td> 
     <td>Column 1</td> 
     <td>Column 2</td> 
     <td>Column 3</td> 
     <td>Column 4</td> 
    </tr> 
    <tr id="one"> 
     <td>Service 1</td> 
     <td>12</td> 
     <td>45</td> 
     <td>45</td> 
     <td>54</td> 
    </tr> 
    <tr id="two"> 
     <td>Service 2</td> 
     <td>8</td> 
     <td>42</td> 
     <td>35</td> 
     <td>23</td> 
    </tr> 
    <tr id="three"> 
     <td>Service 3</td> 
     <td>6</td> 
     <td>65</td> 
     <td>16</td> 
     <td>26</td> 
    </tr> 
    <tr id="result" style="background:silver;"> 
     <td>TOTAL:</td> 
     <td id="total1">0</td> 
     <td>0</td> 
     <td></td> 
     <td></td> 
    </tr> 
</table> 
<br>ADD LINE: 
<select id="select_stud"> 
    <option>-- Select --</option> 
    <option>one</option> 
    <option>two</option> 
    <option>three</option> 
</select> 

JS:

$(document).ready(function() { 
    $('#one').hide(); 
    $('#two').hide(); 
    $('#three').hide(); 

    $('#select_stud').change(function() { 
    $('#'+$(this).val()).show(); 
    }) 
}); 


$("#sum_table tr:last td:not(:first,:last)").text(function(i){ 
    var t = 0; 
    $(this).parent().prevAll().find("td:nth-child("+(i+2)+")").each(function(){ 
     t += parseInt($(this).text(), 10) || 0; 
    }); 
    return "= " + t; 
}); 

此外,我需要計算只有2列。

這裏是全碼:http://jsfiddle.net/stanencendo/u7a27vth/9/

感謝。

回答

0

這裏是你正在嘗試做一個例子:http://jsfiddle.net/u7a27vth/10/

只查找可見行計算的總和時,您可以添加這樣的條件:

if ($(this).parent().css('display') != 'none') 

你也希望每次添加新列時更新總和。您可以通過在功能包裝的總和計算(在這種情況下,updateSums)做到這一點,你改變函數中調用它的選擇元素:

$('#select_stud').change(function() { 
    $('#'+$(this).val()).show(); 
    updateSums(); 
}) 

這就是說,你的做法可能不是最好的辦法來處理這個問題。通常情況下,您希望您的視圖來自您的數據,而不是其他方式。

編輯:正如在評論中指出,如果你想最後一欄進行計算,以及,你需要改變$("#sum_table tr:last td:not(:first,:last)")$("#sum_table tr:last td:not(:first)")

這是我不清楚這是否是你的意圖。

+1

很棒的工作!也不要忘了修改你選擇器:$(「#sum_table tr:last td:not(:first,**:last **)」)to $(「#sum_table tr:last td:not(**:first **)「)包括最後一列:) – ymz 2014-11-24 01:39:28

+0

太好了,謝謝。工作正常。 – 2014-11-24 11:08:34

+0

我需要只計算兩列,COLUMN 1和COLUMN 2排除任何其他列。 – 2014-11-24 12:01:08

0
$("#sum_table tr:last td:not(:first,:last)").text(function(i){ 
    var t = 0; 
    $(this).parent().prevAll().find("td:nth-child("+(i+2)+")").filter(":visible").each(function(){ 
     t += parseInt($(this).text(), 10) || 0; 
    }); 
    return "= " + t; 
}); 
+0

根本無法使用問題中提供的代碼。 – laffuste 2014-11-24 02:53:56