gpt4 book ai didi

jquery - 如何计算 HTML 表格列中所有输入字段的总和并将值显示在单元格中?

转载 作者:行者123 更新时间:2023-12-01 06:33:47 27 4
gpt4 key购买 nike

我需要对表中每列中的所有输入字段进行求和,并反射(reflect)每列下的单元格中每列的总和,然后对这些单元格求和并在标记为“季度总和”的单元格中显示它们的结果总计”。

我有一个用于计算数字的 JQuery,但它对我不起作用,而且我不知道如何对每个季度列的总计进行求和并将其显示在其下方的单元格中。你能帮我解决这个问题吗?如何显示每列的总计?如何将这些列的总数汇总到一个单元格中?

这是我的 HTML:

<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>Exercise</th>
<th>Q1</th>
<th>Q2</th>
<th>Q3</th>
</tr>
</thead>
<tr>
<td>Exercise #1</td>
<td>
<input type="text" class="txt input-mini" />
</td>
<td>
<input type="text" class="txt input-mini" />
</td>
<td>
<input type="text" class="txt input-mini" />
</td>
</tr>
<tr>
<td>Exercise #2</td>
<td>
<input type="text" class="txt input-mini" />
</td>
<td>
<input type="text" class="txt input-mini" />
</td>
<td>
<input type="text" class="txt input-mini" />
</td>
</tr>
<tbody>
</tbody>
</table>
<div class="row-fluid">
<div class="span5">
<div class="form-inline">
<label>Sum of Quarters' Total</label>
<input id="sum" type="text" class="input-medium" />
</div>
</div>
<div class="span7">
<div class="form-inline">
<label>Quarters' Total</label>
<input type="text" class="input-mini" />
<input type="text" class="input-mini" />
<input type="text" class="input-mini" />

</div>
</div>
</div>
</div>

这是 JQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script>
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function () {
$(this).keyup(function () {
calculateSum();
});
});
});

function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});

//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>

这是问题的快照: enter image description here

最佳答案

演示 http://jsfiddle.net/mattydsw/gk5kyc7w/1/

总的只需改变

$("#sum").html(sum.toFixed(2));

$("#sum").val(sum.toFixed(2));

对于季度:

    var sumQ = [];
for (var i=1; i<=3; i++) {
sumQ[i] = 0;
$('td:nth-child('+(i+1)+')').find(".txt").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sumQ[i] += parseFloat(this.value);
}
});
$(".span7").find('input').eq(i-1).val(sumQ[i].toFixed(2));
}

关于jquery - 如何计算 HTML 表格列中所有输入字段的总和并将值显示在单元格中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27217468/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com