我需要对表中每列中的所有输入字段求和,并反映每列下单元格中每列的总和,然后对这些单元格求和,并在标记为' Sum的单元格中显示它们的结果of Quarters'总'
我有一个用于计算数字的JQuery,但它不能与我合作,而且我不知道如何将每个Quarter列的总和相加并将其显示在它下面的单元格中。你能帮帮我吗?如何显示每列的总数?如何将这些列的总和合并为一个单元格?
这是我的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>
这是问题的快照:
答案 0 :(得分:5)
DEMO 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));
}
答案 1 :(得分:0)
改为此。希望就是你想要的
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).val()) && $(this).val().length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").val(sum.toFixed(2));
}
小提琴here