获取javascript

时间:2017-04-27 22:14:33

标签: javascript jquery

如何得到最后一列的总和和平均值。在我的代码中,如果表有一行,两行和三行,它将不会得到正确的值。这只适用于有4行的表。我知道我的错代码,但我无法弄清楚循环如何在.each函数。

重要说明:这与keyup事件一起运行以更新表数据。它不仅仅是一个显示器。确切地说,它是一个更新表单。

所需的输出

Item  | value1 | value 2 | value3 |value 4 | Average 
 01        90      88       87      80        82.25

Total average   82.25     result of 82.25/1 number of row

if two rows

Item  | value1 | value 2 | value3 |value 4 | Average 
 01       90      88       87      80        82.25
 02       80      85       86      84        83.75

    Total average   83     result of (82.25+83.75)/2 number of rows

但结果出现了多个循环

Here is the console.log(totalAverage)
86.25
176
264.75
353.5
442.25
86.25
176
264.75
353.5
442.25

问题:如何抑制或跳过这些不必要的值。我只需要86.25来显示总数。注意:这只是现在的单行并且已经发生了这种错误,如果表有多个多少则多少那么行?

HTML

<tr>
 <th colspan="12"><h4>Card</h4></th>
 </tr>
 <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'=>'0']) !!}</td>
 <td colspan="2">{!! Form::text('term_2[]',$subject->term_2,['class'=>'form-control','name[]'=>'term_2','id[]'=>'term_2','value'=>'0']) !!}</td>
<td colspan="2">{!! Form::text('term_3[]',$subject->term_3,['class'=>'form-control','name[]'=>'term_3','id[]'=>'term_4','value'=>'0']) !!}</td>
 <td colspan="2">{!! Form::text('term_4[]',$subject->term_4,['class'=>'form-control','name[]'=>'term_4','id[]'=>'term_4','value'=>'0']) !!}</td>
 <td colspan="2" class="average" id="average" value="0"> 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' => '0']) !!}</th>
 </tr>

Javascript代码段

$("input").on("keyup", function(){
 $("tbody tr").each(function() {
    var col=1;
    var tr =1;
    var t = 0;
    var a = 0;

 $(this).children('td').not(':last').each(function () {
 var number = ($(this).children('input').length == 0) ? $(this).html() : $(this).children('input').first().val();
                   // console.log(number);
                   // console.log(col);
                    t += parseInt(number);
                   // console.log(t);

                    a = t/col;
                    col++;

          });
           $(this).children('td').last().html(a);//last td of the  row
          // console.log(a);
           col=1;      
           tr++;


});
    calcTotalave();

    });

        // calculate total average
        function calcTotalave() {
            var totalAve = 0;
            var tot=0;
            var c = 2;
            var count =0;
            $( ".average" ).each(function() {
               // console.log($(this).html());

                var thisAve = parseFloat($(this).html());

                if(!thisAve || thisAve === NaN || thisAve == "") {
                    thisAve = 0;
                }


                totalAve += thisAve;  
                   //alert('count'+thisAve+totalAve); 
                   console.log(totalAve); 

                count++;

            });
                c++;
                totalAve = totalAve/c;
               // console.log(totalAve);

                $("#total-ave").val(totalAve);


        }

1 个答案:

答案 0 :(得分:0)

更新:在下面添加评论,按空格键运行,基于以下功能。 小提琴是循环遍历并按行计算单元格,因此不需要.average类。您需要根据数据库输出调整html表格布局。

calcTotalave();

});

    // calculate total average
    function calcTotalave() {
        var totalAve = 0;

        $( ".average" ).each(function() {

            var thisAve = parseFloat($(this).text()) || 0; // always return a number

            totalAve += thisAve; 

        });

        var Aver = totalAve / $('.average').length;  
        console.log(totalAve); 

        $("#total-ave").text(Aver);    
    }

而不是将每个单元格分类为.average,您可以使用选择器定位给定行的所有单元格td

$('input').change(function() {
    calTotalAverages(); // the magic and collect the total average
});

function calTotalAverages(){
  var SumAve = 0, nums = 0; // to collect total averages and the number of rows
  $('tr').each(function(i) {
    if (i > 0) { // ignore the first row
      var $this = $(this);
      SumAve += calcRowAve($this); // add up the returned averages and run the function
      nums ++; // count the rows
    }
  }); // cycle through each row

  var sum = (SumAve / nums);
  $('#total-ave').text(sum.toFixed(2)); // display the total average
  
  return sum; // return the total average
}

// calculate total average
function calcRowAve(targetRow) {
  var totalAve = 0,
    targetCells = targetRow.children(),
    targLength = targetCells.length - 2; // total number of values in a row

  targetCells.each(function(i) {
    if (i > 0 && i <= targLength) {
      var thisAve = parseFloat($('input',this).val()) || parseFloat($(this).text()) || 0; // always return a number
      totalAve += thisAve;
    } // check to ignore the first cell and the last

  });

  var Aver = totalAve / targLength; // get the average
  targetCells.last().text(Aver); // update the last cell of the row
  return Aver;  // return the average for this row
}
#total-ave {
  position: fixed;
  right: 2em;
  top: 8em;
}

input{
  width: 5em;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <th>item 1</th>
    <th>value 1</th>
    <th>value 2</th>
    <th>value 3</th>
    <th>value 4</th>
    <th>average</th>
  </tr>
  <tr>
    <td>1</td>
    <td>90</td>
    <td>88</td>
    <td>87</td>
    <td>80</td>
    <td></td>
  </tr>
  <tr>
    <td>2</td>
    <td>80</td>
    <td>85</td>
    <td>86</td>
    <td>84</td>
    <td></td>
  </tr>
  <tr>
    <td>3</td>
    <td><input type='number'></td>
    <td><input type='number'></td>
    <td><input type='number'></td>
    <td><input type='number'></td>
    <td></td>
  </tr>
</table>

<div id='total-ave'></div>