Pregunta

The idea is to refresh total value every time checkbox checked.

My HTML looks like that

<table class="table table-striped table-bordered table-hover">


                                <tbody>
...
                                <tr>
                                    <td><input type="checkbox" name="services[]" value="5" class="services"></td>
                                    <td>Sample</td>
                                     <td id="srv_5">60</td>
                                    </tr> 
 ...                    
</tbody>

                        </table>

Function looks like that

function calcServicesTotal() {
    var total=0;
    $('.services').each(function () {
        var id = parseInt($(this).val());
        var price = parseInt($("#srv_" + id).text());
        if (this.checked) {
            total = total + price;
            console.log("id - " + id + " price - " + price);
        }
        else {
            if (total > 0)
                total = total - price;
        }

    });
    console.log("total - " + total);
}

The problem is I can see console.log("id - " + id + " price - " + price); right values but total stays every time 0. What am I doing wrong?

¿Fue útil?

Solución

This makes no sense

else {
    if (total > 0)
        total = total - price;
}

That else makes NO sense at all, so if the checkbox is unchecked, you subtract. So if the first checkbox is checked it will make total > 0 and all checkboxes are unchecked, you start subtracting their values until it is zero.

That else check does not belong there.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top