Javascript Checkboxes Incorrect Calculating
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
Solution 1:
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"));
});
Solution 2:
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"));
});
Solution 3:
try
$("input[type=checkbox]").click(function() {
recalculate();
});
rel attribute is for anchor tag
and instead of rel attribute use value or id
Solution 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;
});
Post a Comment for "Javascript Checkboxes Incorrect Calculating"