Javascript checkboxes incorrect calculating

2019-07-10 02:50发布

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

});

4条回答
Lonely孤独者°
2楼-- · 2019-07-10 02:52

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"));
});
查看更多
欢心
3楼-- · 2019-07-10 02:59

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"));
 });
查看更多
Ridiculous、
4楼-- · 2019-07-10 03:05

try

$("input[type=checkbox]").click(function() {
        recalculate();
    });

rel attribute is for anchor tag

and instead of rel attribute use value or id

查看更多
Lonely孤独者°
5楼-- · 2019-07-10 03:06

You are resetting the sum for each checkbox in the code below:

$("input[type=checkbox]:checked").each(function() {
     sum = parseInt($(this).attr("rel")) + base;
});
查看更多
登录 后发表回答