简体   繁体   中英

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: https://jsfiddle.net/600rzptn/

You can do it like following.

 $('.selectproduct').change(function() { var totalPrice = 0; $('.selectproduct:checked').each(function() { totalPrice += $(this).data('price') * $(this).next('input').val(); }); $('.price').html(totalPrice); }); //to change total price on changing textbox value $('input[type="text"]').keyup(function() { $('.selectproduct:first').change(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="selectproduct" type="checkbox" name="item0" data-price="5" />First <input type="text" name="qty0" /> <br/> <input class="selectproduct" type="checkbox" name="item1" data-price="7" />Second <input type="text" name="qty1" /> <br/> Total Price: $<span class="price">0</span> 

Change your calculation line to:

totalPrice += parseInt($(this).data('price'), 10) * $(this).next().val();

jsFiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM