如何乘以该值并得到总数。我尝试下面附带的代码。 当我添加这两个数字,它工作正常。但当我乘以两个值得到问题。 这是我如何添加值
sum += Number($(this).val());
而不是+我把*这个符号
sum *= Number($(this).val());
结果未显示且没有错误。我在下面附上代码,请看代码并给我一个好的答案谢谢。
此表格
<div class="form-group">
<label for="" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<input type="text" class="form-control price" id="price" name="price" placeholder="price" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Qty</label>
<div class="col-sm-10">
<input type="text" class="form-control price" id="qty" name="qty" placeholder="qty" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Total Cost</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="total_cost" name="total_cost" placeholder="Total Cost" required>
</div>
</div>
这是jQuery
function total()
{
// we used jQuery 'keyup' to trigger the computation as the user type
$('.price').keyup(function () {
// initialize the sum (total price) to zero
var sum = 0;
// we use jQuery each() to loop through all the textbox with 'price' class
// and compute the sum for each loop
$('.price').each(function() {
sum += Number($(this).val());
});
// set the computed value to 'totalPrice' textbox
$('#total_cost').val(sum);
});
}
答案 0 :(得分:0)
您需要初始化sum =1
,因为sum = 0
将在乘法时始终为0
所以: -
var sum = 1;
sum = sum * Number($(this).val());
或者
var sum = 1;
sum *= Number($(this).val());
工作代码段: -
$(document).ready(function(){
$('.price').keyup(function(){
var sum = 1;
$('.price').each(function() {
if($(this).val()){
sum *= Number($(this).val());
}
});
$('#total_cost').val(sum);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<input type="text" class="form-control price" id="price" name="price" placeholder="price" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Qty</label>
<div class="col-sm-10">
<input type="text" class="form-control price" id="qty" name="qty" placeholder="qty" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Total Cost</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="total_cost" name="total_cost" placeholder="Total Cost" required>
</div>
</div>
&#13;