我想获取填充文本框值的平均值,并在平均文本框中显示
问题:我可以计算填充文本框的总和 但我不知道如何获得填充文本框的数量并获得它们的平均值 就像两个文本框是值为5和6的文件一样,则总数应为11,平均值应为5.5(11/2)
我的代码如下,请检查
HTML文件
<input type="text" value="" name="prj_usgjan" class="prj_usage" id="prj_usgjan">
<input type="text" value="" name="prj_usgfeb" class="prj_usage" id="prj_usgfeb">
<input type="text" value="" name="prj_usgmar" class="prj_usage" id="prj_usgmar">
<input type="text" value="" name="prj_usgapr" class="prj_usage" id="prj_usgapr">
<input type="text" value="" name="prj_usgmay" class="prj_usage" id="prj_usgmay">
<input type="text" value="" name="prj_usgjun" class="prj_usage" id="prj_usgjun">
<input type="text" value="" name="prj_usgjul" class="prj_usage" id="prj_usgjul">
<input type="text" value="" name="prj_usgaug" class="prj_usage" id="prj_usgaug">
<input type="text" value="" name="prj_usgsep" class="prj_usage" id="prj_usgsep">
<input type="text" value="" name="prj_usgoct" class="prj_usage" id="prj_usgoct">
<input type="text" value="" name="prj_usgnov" class="prj_usage" id="prj_usgnov">
<input type="text" value="" name="prj_usgdec" class="prj_usage" id="prj_usgdec">
<input type="text" readonly="readonly" name="prj_usgtot" class="prj_usgtot" id="prj_usgtot">
<input type="text" readonly="readonly" name="prj_usgavg" class="prj_usgavg" id="prj_usgavg">
Js档案
jQuery(".prj_usage").keyup(function(){
var sum = 0;
jQuery('.prj_usage').each(function() {
sum += Number(jQuery(this).val());
});
jQuery('#prj_usgtot').val(sum); // get the sum and show that in total text box
});
答案 0 :(得分:1)
我在这里找到解决方案,试试这个: -
jQuery(".prj_usage").keyup(function(){
var sum = 0;
var avg = 0;
jQuery('.prj_usage').each(function() {
sum += Number(jQuery(this).val());
});
var $allx = jQuery(':text.prj_usage');
var $emptyx = $allx.filter('[value=""]');
var num = $allx.length - $emptyx.length ;
if(num > 0){ avg = Number(sum/num); }
jQuery('#prj_usgtot').val(sum);
jQuery('#prj_usgavg').val(avg.toFixed(2));
});