dimanche 11 septembre 2016

Multiply checkbox data attribute with input value

Each time I check any checkbox, I want to multiply the data-price attribute with the value of the input field associated with the checkbox. I need to calculate the sum of all these multiplications.

HTML:

<input class="selectproduct" type="checkbox" name="item0" data-price="5"/>First 
<input type="text" class="qty0" name="qty0"/>
<br/>
<input class="selectproduct" type="checkbox" name="item1" data-price="7"/>Second 
<input type="text" class="qty1" name="qty1"/>
<br/>
Total Price: $<span class="price">0</span>

JS:

$('.selectproduct').on("change", function () {
    var totalPrice = 0;

    $('.selectproduct:checked').each(function () {
        totalPrice += parseInt($(this).data('price'), 10);
    });

    $('.price').html(totalPrice);
});

I'm currently able to sum the price according to the checkbox but I can't figure out how to multiply it with the associated input field whenever there is a change. How do I constantly update the sum whenever the input field changes?

Here's the fiddle: http://ift.tt/2cnOM6s




Aucun commentaire:

Enregistrer un commentaire