我需要将所有价格加起来并乘以数量。问题是只有第一个字段计算好,其他字段先取价格值。请帮忙 这是我现在来的:
$('.orderForm__item').on('input', function() {
var totalSum = 0;
$('.quantity, .price').each(function() {
var quantity = $(this).val();
var price = $('.price').attr('value');
if ($.isNumeric(quantity)) {
totalSum += parseFloat(quantity) * parseFloat(price);
}
});
$('#total').text(totalSum);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" class="orderForm">
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="1.70">(1.70 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="3">(3.0 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="15">(15 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="1.7">(1.70 KM)</span><br>
</div>
</form>
Total: <output id="total"></output>
&#13;
答案 0 :(得分:1)
each
orderForm__item
quantity
,每个项目price
,$('.orderForm__item').on('input', function() {
var totalSum = 0;
$('.orderForm__item').each(function() {
var quantity = $(this).find('.quantity').val();
var price = $(this).find('.price').attr('value');
if ($.isNumeric(quantity)) {
totalSum += parseFloat(quantity) * parseFloat(price);
}
});
$('#total').text(totalSum);
});
:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" class="orderForm">
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="1.70">(1.70 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="3">(3.0 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="15">(15 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="1.7">(1.70 KM)</span><br>
</div>
</form>
Total: <output id="total"></output>
{{1}}