jQuery 实现表格列合计
用jQuery实现表格列的合计功能,当单元格的值发生变化时,合计行自动统计个单元格的值。
1.编写html
1: <table id="table-fund">
2: <caption class="table-caption-legend">
3: (单位:万元)</caption>
4: <thead>
5: <tr>
6: <th colspan="3">经费到位情况</th>
7: </tr>
8: <tr>
9: <th>科目
10: </th>
11: <th>预算数</th>
12: <th>到位数</th>
13: </tr>
14: </thead>
15: <tr>
16: <td>1.省科技经费
17: </td>
18: <td>
19: <input id="SouProSciTech" type="text" />
20: </td>
21: <td>
22: <input id="ProSciTechAvailable" type="text" /></td>
23: </tr>
24: <tr>
25: <td>2.单位自筹
26: </td>
27: <td>
28: <input id="SouUnitSelfFinanc" type="text" />
29: </td>
30: <td>
31: <input id="UnitSelfFinancAvailable" type="text" /></td>
32: </tr>
33: <tr>
34: <td>3.银行贷款
35: </td>
36: <td>
37: <input id="SouBankloans" type="text" />
38: </td>
39: <td>
40: <input id="BankloansAvailable" type="text" /></td>
41: </tr>
42: <tr>
43: <td>
44: <span class="totall">合</span><span class="totall">计</span>
45: </td>
46: <td>
47: <input id="TotalSou" readonly="readonly" type="text" />
48: </td>
49: <td>
50: <input id="TotalSouAvailable" readonly="readonly" type="text" />
51: </td>
52: </tr>
53: </table>
2. Script实现
2.1 为每个input绑定事件
实现在单元格值发生变化时,合计行的单元格的值自行发生变化,这里采用.each()遍历input并为其绑定函数keyup(这里不采用change),在keyup事件发生时进行合计。
1: $("#table-fund tr").each(function () {
2: $(this).find("td:eq(1) input:not(#TotalSou)").keyup(function () {
3: totalSouFund();//调用合计方法
4: });
5: });
这里遍历除统计单元格之外的每个input,以上代码遍历第二列的输入框,在:not()中排除合计单元格的input。在input的keyup触发时调用合计方法。
2.2 实现合计
1: function totalSouFund() {
2: totalSou = 0;
3: $("#table-fund tr").each(function () {
4: $(this).find("td:eq(1) input:not(#TotalSou)").each(function () {
5: totalSou += getNumValue($(this)) ;
6: $("#TotalSou").val(Number(totalSou.toFixed(4)));
7: });
8: });
9: }
(1) totalSou用来存储合计值,在每次调用该函数时把totalSou置0,然后遍历每个单元格中的值进行累加;
(2) getNumValue()用来获取文本框的值,返回float;
1: function getNumValue(controlid) {
2: /// <summary>
3: /// Get a number from input tag which type is text
4: /// </summary>
5: /// <param name="controlid">id of input control</param>
6: /// <returns type="">float or 0</returns>
7: var num = controlid.val();
8: if (validateInput(num)) {
9: num = parseFloat(num);
10: }
11: else {
12: controlid.val("");
13: num = 0;
14: }
15: return num;
16: }
(2.1) validateInput() 返回一个Bool值用来验证输入的值是否有效,确保getNumValue返回一个有效数值
1: function validateInput(inputstr) {
2: /// <summary>
3: /// validate a value
4: /// </summary>
5: /// <param name="inputstr"></param>
6: /// <returns type="">bool</returns>
7: flag = false;
8: if (inputstr != "") {
9: if (isNaN(inputstr)) {
10: flag = false; //如果输入字符不是数字
11: }
12: else {//输入数字但是小于0
13: if (parseFloat(inputstr) < 0)
14: flag = false;
15: else
16: flag = true;
17: }
18: }
19: return flag;
20: }
2.3 处理javaScript中浮点数计算的出现的问题
1: $("#TotalSou").val(Number(totalSou.toFixed(4)));
注:这里用Number(totalSou.toFixed(4))保留四位小数,但是其它单元格中输入超过四位小数时在此并没有做相应的处理。你也可以做进一改进,只传入合计控件ID和列的索引值写更少的代码。
<summary>随笔,若有不足之处和好的建议,欢迎交流学习}</summary>