我如何才能获得总计动态创建的每个字段值
<div class="rf-row count-container">
<input class="total">
<div class="row">
<input class="add-monthly">
</div>
<div class="row">
<input class="add-monthly">
</div>
<div class="row">
<input class="add-monthly">
</div>
</div>
答案 0 :(得分:0)
由于您已经标记了jquery
,因此以下是您遍历类input
的所有add-monthly
并将其值求和的方法,最后返回总和值:
function sumFields() {
var totalSum = 0;
$("input.add-monthly").each(function () {
totalSum += $(this).val();
});
return totalSum;
}
答案 1 :(得分:0)
请检查此代码,这可能有帮助
<!DOCTYPE html>
<html>
<head>
Demo
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="rf-row count-container">
<input class="total">
<div class="row">
<input class="add-monthly" value="5">
</div>
<div class="row">
<input class="add-monthly" value="5">
</div>
<div class="row">
<input class="add-monthly" value="5">
</div>
</div>
<script>
$(document).ready(function(){
var value = 0;
$('.count-container .row').each(function(){
value += parseInt($(this).find('.add-monthly').val()) ? parseInt($(this).find('.add-monthly').val()) : 0
})
$('.total').val(value);
});
</script>
</body>
</html>
答案 2 :(得分:0)
var classes = document.getElementsByClassName('add-monthly')
classes = [...classes]
var result = classes
.map(item => +item.value)
.reduce((a, b) => a + b, 0);
document.getElementsByClassName('sum-monthly')[0].value = result
console.log('summ', result)
<div class="rf-row count-container">
SUM: <input class="sum-monthly"/><br/>
<div class="sub-rf-row">
<input class="add-monthly" type="number" value="1">
</div>
<div class="sub-rf-row">
<input class="add-monthly" type="number" value="4">
</div>
<div class="sub-rf-row template">
<input class="add-monthly" type="number" value="0">
</div>
</div>
答案 3 :(得分:0)
如果要动态添加input
字段,建议将更改功能委托给父级.count-container
。触发事件后,我将遍历.add-monthly
字段以总结其值。为了帮助JavaScript
理解这些值是浮点数(因为我假设我们正在处理货币),所以我使用parseFloat()以确保可以将这些值添加到总和中。最后,我将.sum-monthly
的值设置为使用toFixed()来使用定点表示法格式化数字(同样,我假设我们正在处理货币)。
$(document).ready(function() {
$('.count-container').on('change', '.add-monthly', function() {
let total = 0;
$('.add-monthly').each(function() {
total += parseFloat($(this).val()) || 0;
});
$('.sum-monthly').val(total.toFixed(2));
}).find('.add-monthly').change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rf-row count-container">
<input class="sum-monthly" readonly>
<div class="sub-rf-row">
<input class="add-monthly">
</div>
<div class="sub-rf-row">
<input class="add-monthly">
</div>
<div class="sub-rf-row template">
<input class="add-monthly">
</div>
</div>