简体   繁体   English

将复选框数据属性与输入值相乘

[英]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. 每次我选中任何复选框时,我都想将data-price属性乘以与该复选框关联的输入字段的值。 I need to calculate the sum of all these multiplications. 我需要计算所有这些乘法的总和。

HTML: 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: 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/ 这是小提琴: 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 jsFiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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