jQuery checkbox and select - sum the values and add in var

前端 未结 6 1109
礼貌的吻别
礼貌的吻别 2020-12-17 07:10

The explanation is below the code:

The code for HTML is :

Add-ons

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 07:35

    I believe that you're simply missing a block for your if statement in the each function: you don't want to increment total unless this.checked is true. Furthermore, you want to convert all strings to numbers so that you don't get string concatenation from + - I've used parseInt. Also, from your description, it seems like you only want to add the value from the option once, not each time through the loop, so use that to initialize total:

    $cbs.click(function()
    {
        var total = parseInt($("#more").val());
    
        $cbs.each(function()
        {
            if (this.checked)
                total += parseInt(this.value);
        });
    
        $("#usertotal").text(total);
    });
    

    But you also want to do this calculation and update when the select changes, so you should pull this loop out into a separate function and call it using click:

    function calculateTotal()
    {
        var total = parseInt($("#more").val());
    
        $cbs.each(function()
        {
            if (this.checked)
                total += parseInt(this.value);
        });
    
        $("#usertotal").text(total);
    }
    
    $("#more").change(calculateTotal);
    $cbs.click(calculateTotal);
    

提交回复
热议问题