[英]What is the easiest way to calculate total price and quantities for multiple items in javascript?
I have a number of inputs such as:我有许多输入,例如:
<input type="number" name="qty[]" data-price="123.99" value="0" class="qtyfield" min="0">
<input type="number" name="qty[]" data-price="222.11" value="0" class="qtyfield" min="0">
<input type="number" name="qty[]" data-price="25.68" value="0" class="qtyfield" min="0">
if someone selects a quantity from the first one of 6 and the second example of quantity of 8 I need a running total to be calculated as any changes occur.如果有人从 6 中的第一个和 8 的第二个示例中选择一个数量,我需要在发生任何变化时计算运行总数。
If the point here is to get running total of your quantities, weighted by data-price
value, you may simply listen for changes and update result value with reduce()
'ed sum of input field multiplied by data-price
:如果这里的重点是获得按
data-price
值加权的数量的运行总和,您可以简单地监听更改并使用reduce()
'ed 输入字段的总和乘以data-price
更新结果值:
$('.qtyfield').on('change', () => { const total = [...$('.qtyfield')] .map(input => $(input).val()*$(input).attr('data-price')) .reduce((t,q) => t+q,0) $('#result').text(total) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="number" name="qty[]" data-price="1" value="0" class="qtyfield" min="0"> <input type="number" name="qty[]" data-price="2" value="0" class="qtyfield" min="0"> <input type="number" name="qty[]" data-price="3" value="0" class="qtyfield" min="0"> <div id="result"></div>
Note: I have changed data-price
values for simplicity sake注意:为简单起见,我更改了
data-price
值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.