Counter does not work

2

I have a table with different foods and for each food a checkbox. I want for each selected food to be adding their kcals and show them at the end. The kcals of each food are double type. I have made the following code but it does not continue adding the rest of the food only the first one and it does not add well either.

Function to calculate the sum:

function contador(checkbox,kcal) {
    caloriasT = 0;
    if($(checkbox).is(":checked")){
        caloriasT+=kcal;
    }else{
        caloriasT=caloriasT-kcal;
    }
    $("#kcals").html(caloriasT);
}

Checkbox that calls the function:

<td class="text-center">
    <input type="checkbox" value="" 
        onclick="cambiarEstado(this,'{{$alimentoid}}','{{$cantidadid}}','{{$comentarioid}}');
        contador(this,'{{$a->kcal}}')"
    >
</td>

Paragraph where the sum is shown:

<div class="row" style=" padding-left: 25px;">
    <p class="text-left col-md-3 col-lg-3" style="font-size:18px;width:250px;">
        <strong>Kcals seleccionadas: </strong>
    </p>
    <p class="text-left col-md-1 col-lg-1" style="font-size: 18px" id="kcals">

    </p> 
</div>
    
asked by Roledi 28.06.2017 в 12:57
source

1 answer

1
function contador(checkbox,kcal) {
caloriasT = 0;
if($(checkbox).is(":checked")){
    caloriasT+=parseFloat(kcal);
}
$("#kcals").html(caloriasT);
}

You should not subtract the values. As every time you make the call you put calories to zero, you do not need to subtract anything, just add the ones that are checked.

Also, put the values as NUMBER, not as string.

    
answered by 28.06.2017 / 13:46
source