2016-01-12 39 views
-5

我显示选中某些复选框时复选框值的总数。它的工作正常。我需要在页面加载时显示所有复选框值总计,如果选中或不选,则无关紧要。这也工作正常。但最后如果我不勾选所有的复选框,它也应该显示整个复选框值总数..我将如何实现这一目标?使用jquery显示记录的总和

<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

请不要做出同样的问题,不同岗位,,你可能会通过编辑你自己的问题http://stackoverflow.com/questions/34735834/jquery-show-the-sum-total-when问同样的事情-checkbox IS-检查/ 34736130#34736130 –

回答

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")); 
}); 
0

更改这一部分:

$(".tot_amount").change(function (event) { 
    getTotal($(".tot_amount:checked")); 
}); 

您应该检查选中的元素

量3210

例如

$(".tot_amount").change(function (event) { 
    if($('.tot_amount').length === 0) { 
     getTotal($('.tot_amount')); 
    } else { 
     getTotal($(".tot_amount:checked")); 
    } 
}); 
1

DEMO按您的要求...检查出DEMO

$(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); 
});