【发布时间】:2022-01-25 05:00:06
【问题描述】:
我试图获得 8 个表单输入的平均值,而我想出的最好方法是将结果(只读)单元格中的当前总数除以 8。使用我的方法,当用户输入时,在输入所有 8 个必需的输入之前,平均值是不正确的。但好消息是,我发现 [这篇优秀的帖子][1] 几乎对我有用 - 除了它使用表格,脚本在第 3 行引用了它:
$('table tr').each(function() {
..但我的表单对每个输入字段行使用 div。
谁能回答如何调整下面的脚本使其适用于 div 而不是表格?
这是上面链接中的示例:
$(document).ready(function() {
$(document).on("input", ".kd1", function() {
$('table tr').each(function() {
// variables for holding total and count
var total = 0,
count = 0;
// get all input fields and iterate over them
$('.kd1', this).each(function() {
// check the value is non-empty
if (this.value.trim() != '') {
// increment count for calculating average
count++;
// update total based on input value
// treat input value as 0 if number parsing produces NaN
total += (Number(this.value.trim()) || 0);
}
});
// calculate and update the average although treat as zero if NaN
$('.result1', this).val(total / count || 0);
});
});
});
和html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<tr>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='result1'>
</td>
</tr>
<tr>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='kd1'>
</td>
<td>
<input type='text' size='5' class='result1'>
</td>
</tr>
</table>
最终解决方案 - 这适用于 DIV:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avcalc">
<div>
<input type='text' size='5' class='kd1'>
</div>
<div>
<input type='text' size='5' class='kd1'>
</div>
<div>
<input type='text' size='5' class='kd1'>
</div>
<div>
<input type='text' size='5' class='kd1'>
</div>
<div>
<input type='text' size='5' class='kd1'>
</div>
<div>
<input type='text' size='5' class='result1'>
</div>
</div>
$(document).ready(function() {
$(document).on("input", ".kd1", function() {
$('div.avcalc').each(function(){
// variables for holding total and count
var total = 0,
count = 0;
// get all input fields and iterate over them
$('.kd1', this).each(function() {
// check the value is non-empty
if (this.value.trim() != '') {
// increment count for calculating average
count++;
// update total based on input value
// treat input value as 0 if number parsing produces NaN
total += (Number(this.value.trim()) || 0);
}
});
// calculate and update the average although treat as zero if NaN
$('.result1', this).val(total / count || 0);
});
});
});
【问题讨论】:
标签: html jquery forms input calculation