由于我的代码有多个输入字段,我很困惑放置密钥的位置。我知道只考虑我在javascript中的有限知识,只在一个输入中放入一个密钥。这个输入中的任何一个都应该自动更新平均列。最后它应该自动计算总平均值。希望有人能在这里帮助我。谢谢你!
样本表
Subject | 1stG | secG | 3rdG |4thG | Average
English 0 0 0 0 0 inputs here except for Average
Psychology 0 0 0 0 0
此处的总平均值...
HTML
<tr>
<th colspan="3">Subjects</th>
<th colspan="2">First Grading</th>
<th colspan="2">Second Grading</th>
<th colspan="2">Third Grading</th>
<th colspan="2">Fourth Grading</th>
<th>Average</th>
</tr>
</thead>
<tbody
@foreach($update_card['AllGrade'] as $subject)
{!! Form::hidden('grade_id[]',$subject['grade_id']) !!}
<tr>
<th colspan="3">{!! $subject->subject !!}</th>
<td colspan="2">{!! Form::text('term_1[]',$subject->term_1,['class'=>'form-control','name[]'=>'term_1','id[]'=>'term_1','value'=>'']) !!}</td>
<td colspan="2">{!! Form::text('term_2[]',$subject->term_2,['class'=>'form-control','name[]'=>'term_2','id[]'=>'term_2','value'=>'']) !!}</td>
<td colspan="2">{!! Form::text('term_3[]',$subject->term_3,['class'=>'form-control','name[]'=>'term_3','id[]'=>'term_4','value'=>'']) !!}</td>
<td colspan="2">{!! Form::text('term_4[]',$subject->term_4,['class'=>'form-control','name[]'=>'term_4','id[]'=>'term_4','value'=>'']) !!}</td>
<td colspan="2" class="average" value=""> Average</td>
</tr
@endforeach
<tr>
<th colspan="11">Total Average:</th>
<th>{!! Form::text('scholar_GPA',$update_card->scholar_GPA,['class'=>'form-control total-ave','name' => 'total-ave','id' => 'total-ave','value' => '']) !!}</th>
</tr>
脚本
<script type="text/javascript">
$("tbody tr").each(function() {
var total = 0;
var ave = 0;
var count = 1;
$(this).children('td').not(':last').each(function () {//foreach of the column of the row
//"this" is the current element in the loop
var number = ($(this).children('input').length == 0) ? $(this).html() : $(this).children('input').first().val();
total += parseInt(number);
ave = total/count;
alert(number+' '+total);
alert('td'+count);
count++;
});
alert('last'+ave);
$(this).children('td').last().html(ave);//loop the row
});
</script>
答案 0 :(得分:0)
你走在正确的轨道上。在每个输入上放置一个关键监听器,但让它运行相同的功能来更新平均列。提示:您的当前函数应该是在有任何更改(重新计算)时运行的函数。
如果需要,请查看这个plunker,但一定要先尝试自己!
https://plnkr.co/edit/0fJgNDty9OiW5KeBJbn8
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script src="script.js"></script>
<input type="text" value="0">
<input type="text" name="" id="" value="0" />
<p id="average">0</p>
<script>
function calculateAverage(){
sum = 0
$("input").each(function(){
sum += parseInt($(this).val())
})
$("#average").text(sum)
}
$("input").on("keyup", function(){
calculateAverage()
})
</script>
</html>