Javascript - Рассчитать значение AVG столбца таблицы HTML в Javascript не работает - PullRequest
0 голосов
/ 07 сентября 2018

Работа в Ларавеле. Мне нужно рассчитать среднее значение «Стоимость» Но это не работает. Вот мой код:

<table class="table table-striped table-bordered" id="table">
                    <thead>
                      <tr>
                         <th scope="col">ID</th>
                         <th scope="col">Name</th>
                         <th scope="col">Description</th>
                         <th scope="col">Cost</th>

                      </tr>
                    </thead>
                    <tbody id="myTable">
                    @foreach($detailsa as $invoice)
                        @foreach($invoice->subaccountinvoice as $sub_accounts)
                      <tr>
                          <td scope="row">{{$sub_accounts->codeinvoice}}</td>
                          <td scope="row">{{$sub_accounts->userinvoiceperson->user_name}}</td>
                          <td scope="row"><span>{{$sub_accounts->description}}</span></td>
                          <td scope="row"><span>{{$sub_accounts->amount}}</span></td>
                        </tr>
                         @endforeach
                  @endforeach
                  </tbody>
              </table>
    <span id="val"></span>

{{$ sub_accounts-> amount}} возвращает число

В JavaScript

  <script>
        var table = document.getElementById("myTable"), avgVal, sumVal = 0, 
                    rowCount = table.rows.length - 1;// minus the header

        for(var i = 1; i < table.rows.length; i++)
        {
            sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
        }

        document.getElementById("val").innerHTML = "Average Value = " + parseInt(sumVal / rowCount);
    </script>

Окончательный результат: NaN, кто-нибудь может помочь? Спасибо !

1 Ответ

0 голосов
/ 07 сентября 2018

Кажется, что вы можете изменить table.rows.length - 1 для table.rows.length и i = 1 для i = 0 и добавить .children[0], потому что у вас есть тег span.

var table = document.getElementById("myTable"),
  avgVal, sumVal = 0,
  rowCount = table.rows.length;

for (var i = 0; i < table.rows.length; i++) {
  sumVal += parseInt(table.rows[i].cells[3].children[0].innerHTML);
  
}

document.getElementById("val").innerHTML = "Average Value = " + parseInt(sumVal / rowCount);
<table class="table table-striped table-bordered" id="table">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Name</th>
      <th scope="col">Description</th>
      <th scope="col">Cost</th>
    </tr>
  </thead>
  <tbody id="myTable">
    <tr>
      <td scope="row">1</td>
      <td scope="row">2</td>
      <td scope="row">3</td>
      <td scope="row"><span>10</span></td>
    </tr>
    <tr>
      <td scope="row">1</td>
      <td scope="row">2</td>
      <td scope="row">3</td>
      <td scope="row"><span>30</span></td>
    </tr>
  </tbody>
</table>
<span id="val"></span>
...