问题
Hey guys i have 6 checkboxes and am using their "rel=" values to add up and display a total sum. However if I check box 1 and 3 and 6 the addition ignores box 3 and does not add it to the sum. So basically the lowest and highest checboxes checked are adding up rather than all that are checked.
Wondering if anyone can spot a reason why.
$(document).ready(function() {
function recalculate() {
var sum = 0;
var base = 0;
var d=new Date();
var theDay=d.getDay();
switch (theDay)
{
case 6:
base = 30;
break;
case 0:
base = 30;
break;
default:
base = 49 ;
}
$("input[type=checkbox]:checked").each(function() {
sum = parseInt($(this).attr("rel")) + base;
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
回答1:
At a guess, you need to change this line:
$("input[type=checkbox]:checked").each(function() {
sum = parseInt($(this).attr("rel")) + base;
});
To this:
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel")) + base;
});
With your current code, the sum isn't actually being calculated, since every time you get the rel=
value for the next checkbox, you're overwriting the previous sum value.
EDIT: If you don't want to add the base each time, you can simply move that assignment out of the loop. Like this:
sum = base;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
回答2:
You're overwriting the value of sum
each time in the each()
loop. This is what you can do:
sum = base;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
回答3:
try
$("input[type=checkbox]").click(function() {
recalculate();
});
rel attribute is for anchor tag
and instead of rel attribute use value or id
回答4:
You are resetting the sum for each checkbox in the code below:
$("input[type=checkbox]:checked").each(function() {
sum = parseInt($(this).attr("rel")) + base;
});
来源:https://stackoverflow.com/questions/5755984/javascript-checkboxes-incorrect-calculating