简体   繁体   English

在JavaScript中获取总和和平均值

[英]Getting the sum and average in javascript

How to get the sum and average of the last column.In my code it wont get the correct value if the table has one,two and three rows.This works only on table with 4 rows.I know something wrong with my code but i cant figure it out how the loop works within .each function. 如何获得最后一列的总和和平均值。在我的代码中,如果表具有一,两,三行,它将无法获得正确的值。这仅适用于具有四行的表。我知道我的代码有问题,但我无法弄清楚循环在.each函数中如何工作。

Important note:this runs with keyup event to update table data.Its not just a display.To be exact it is an update form. 重要说明:此命令与keyup事件一起运行以更新表数据。不仅仅是显示,更确切地说,这是一种更新形式。

Desired output 所需的输出

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

But the result comes out with multiple loops 但是结果是通过多个循环得出的

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

Problem:How to suppress or skip this unnecessary values.I only need the 86.25 to display in total-ave.Note: this is only single row right now and have already incountered this miscaculation, how much more if the table has multiple rows then? 问题:如何抑制或跳过这些不必要的值。我只需要86.25才能显示在total-ave中。注意:现在这仅是单行,并且已经克服了这种错误计算,如果表有多行呢?

Html 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 snippet 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);


        }

UPDATED : fiddle below with comments, press space-bar to run, based around the below function. 更新 :在下面用注释摆弄下面的内容,按空格键运行,基于以下功能。 the fiddle is made to cycle through and calc cells by row, so no .average class required. 使小提琴循环通过并按行计算单元格,因此不需要.average类。 You will need to adapt it for your html table layouts as per your database output. 您将需要根据数据库输出将其调整为适合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);    
    }

instead of classing each cell as .average you could use the selector to target all the cells td of a given row: 您可以使用选择器将给定行的所有单元格td作为目标,而不是将每个单元格归类为.average

 $('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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM