我在检查某些复选框时显示复选框值的总和。它的工作正常。我需要在页面加载时显示所有复选框值总计,如果选中或不检查则无关紧要。这也很好。但在最后,如果我取消选中所有复选框,它也应该显示整个复选框值总计..我将如何实现?
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title> Calc</title>
<script type='text/javascript'>
function getTotal(objSelector)
{
var total = 0;
objSelector.each(function () {
total += parseInt($(this).val());
});
$("#tot_amount").val(total.toFixed(3));
if (total == 0) {
$('#total1').val('');
} else {
$('#total1').val(total);
}
}
$(document).ready(function () {
getTotal($(".tot_amount"));
$(".tot_amount").change(function (event) {
getTotal($(".tot_amount:checked"));
});
});
</script>
</head>
<body>
<table border="1">
<tr><td>10<input type="checkbox" class="tot_amount" value="10"></td></tr>
<tr><td>20<input type="checkbox" class="tot_amount" value="20"></td></tr>
<tr><td>30<input type="checkbox" class="tot_amount" value="30"></td></tr>
<tr><td>40<input type="checkbox" class="tot_amount" value="40"></td></tr>
<tr><td>50<input type="checkbox" class="tot_amount" value="50"></td></tr>
<tr><td>60<input type="checkbox" class="tot_amount" value="60"></td></tr>
<tr><td>70<input type="checkbox" class="tot_amount" value="70"></td></tr>
<tr><td>Total<input type="text" id="total1" readonly></td></tr>
</table>
</body>
答案 0 :(得分:3)
试试这个
if($(".tot_amount:checked").length == 0){
getTotal($(".tot_amount"));
}
完整代码
$(".tot_amount").change(function (event) {
if($(".tot_amount:checked").length == 0){
getTotal($(".tot_amount"));
}
else
getTotal($(".tot_amount:checked"));
});
答案 1 :(得分:1)
$(function(){
$(".tot_amount").click(function(event) {
var total = 0;
$(".tot_amount:checked").each(function() {
total += parseInt($(this).val());
});
//$("#tot_amount").val(sum.toFixed(3));
if($(".tot_amount:checked").length == 0){
var total2=0;
$(".tot_amount").each(function() {
total2 += parseInt($(this).val());
});
$('#total1').val(total2);
}else
{
$('#total1').val(total);
}
});
});
$(document).ready(function () {
var total2=0;
$(".tot_amount").each(function() {
total2 += parseInt($(this).val());
});
$('#total1').val(total2);
});
答案 2 :(得分:0)
更改此部分:
$(".tot_amount").change(function (event) {
getTotal($(".tot_amount:checked"));
});
您应该检查已检查元素的数量
e.g。
$(".tot_amount").change(function (event) {
if($('.tot_amount').length === 0) {
getTotal($('.tot_amount'));
} else {
getTotal($(".tot_amount:checked"));
}
});