我正在尝试通过 JavaScript 计算多个动态输入字段的总和。
这是我的主要输入:
<input type="text" name="price[]" id="price" value="" class="form-control" />
这就是我添加输入的方式:
$('.btn-add-srvice').on('click', function(e){
e.preventDefault();
var template = '<input type="text" name="price[]" id="price" class="form-control" />';
$(this).before(template);
});
此后,我有一个自定义函数,可以根据输入计算数据:
function sum() {
var price = document.getElementById('price').value;
var subtotal;
}
它仅计算一个输入(而不是添加的输入)。现在,我想计算使用上述函数创建后显示的每个输入值的价格总和。
预期结果:
input1 = 30
input2 = 30
...... = ...
subtotal = ...
因此,小计变量应填充每个输入的总和。 谢谢。
已更新
现在,我如何计算每行的总和以及小计。在函数下方,您可以找到预期结果图像链接。
我的完整 JavaScript 函数:
$(document).on('keyup keydown change', ".price, .months, #mwst, #rabatt",function () {
var months = document.getElementById('months').value;
var mwst = document.getElementById('mwst').value;
var rabatt = document.getElementById('rabatt').value;
var priceSum = 0;
var monthsSum = 0;
$('.price').each(function(){
priceSum += parseFloat(this.value);
});
$('.months').each(function(){
monthsSum += parseFloat(this.value);
});
var subtotal = priceSum * monthsSum;
var sum = priceSum * months;
var mwstValue = subtotal + 7.7 / 100 * subtotal - subtotal;
document.getElementById('subtotal').value = subtotal.toFixed(2);
document.getElementById('sum').value = subtotal.toFixed(2);
document.getElementById('mwst').value = mwstValue.toFixed(2);
var percentage = (mwst / 100) * subtotal;
var result = subtotal + mwstValue - parseFloat(rabatt);
document.getElementById('total').value = result;
});
我的完整动态插入输入:
$('.btn-add-srvice').on('click', function(e){
e.preventDefault();
var template =
'<div class="col-md-12" style="padding:0">'+
'<div class="col-md-6" style="padding-left:0px">'+
'<div class="form-group">'+
'<select style="width: 100%" id="service_id" name="service_id[]" class="service_id ">'+
'@foreach($servicesList as $sli)'+
'<option value="{{$sli->id}}">{{$sli->name}}</option>'+
'@endforeach'+
'</select>'+
'</div>'+
'</div>'+
'<div class="col-md-3" style="padding-right:0px">'+
'<div class="form-group">'+
'<input type="text" name="price[]" id="price" value="" class="form-control price" />'+
'</div>'+
'</div>'+
'<div class="col-md-1" style="padding-right:0px">'+
'<div class="form-group">'+
'<input type="text" name="months[]" id="months" value="" class="form-control months" />'+
'</div>'+
'</div>'+
'<div class="col-md-2" style="padding-right:0px">'+
'<div class="form-group">'+
'<input type="text" name="sum[]" id="sum" value="" class="form-control sum" />'+
'</div>'+
'</div>'+
'<div>'+
/*'<button type="button" class="btn btn-default btn-xs remove">Remove</button>'+*/
'</div>'+
'</div>';
enter code here
$(this).before(template);
});
以下是链接现在的样子和预期结果: https://ibb.co/sVv3qGF
最佳答案
您正在为多个元素提供相同的 id。改为上课。然后得到他们的总和。
var sum = 0;
$('.price').each(function(){
sum += parseFloat(this.value);
});
关于javascript - 如何在Javascript中计算多个动态输入字段的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801837/