V
V
Vadim Gavrilencko2020-05-14 01:10:58
JavaScript
Vadim Gavrilencko, 2020-05-14 01:10:58

Why doesn't the dynamic table calculator work correctly?

I'm making a dynamic table for the university.
I can't get the last function to work. Does not calculate the sum of the column.
Writes NaN.

<div class="container">
  <p style="display: inline;">Продукты:</p>
  <select name="" id="lstProducts">
    <optgroup label="Овощи">
      <option value="100">Картошка</option>
      <option value="200">Морковь</option>
      <option value="300">Лук</option>
    </optgroup>
    <optgroup label="Фрукты">
      <option value="400">Яблоки</option>
      <option value="500">Бананы</option>
    </optgroup>
    <optgroup label="Напитки">
      <option value="600">Чай</option>
      <option value="700">Кофе</option>
    </optgroup>
  </select>
  <p style="display: inline;">Количество:</p>
  <input id="txtQty" type="text">
  <input value="Добавить в корзину" onclick="AddToCart()" class="bb" type="button">
</div>

<table id="tblOrder">
  
  <thead>
    <tr>
      <th>
        <caption>Ваш заказ</caption>
      </th>
      
    </tr>
    <tr>
      <th>
        <input type="checkbox" onclick="ToggleCheck(this)" />
      </th>
      <th>
        Продукт
      </th>
      <th>
        Цена
      </th>
      <th>
        Количество
      </th>
      <th>
        Сумма
      </th>
      <th>
        
      </th>
    </tr>
    
  </thead>	
  <tbody >		
      
    
  </tbody>
  <tfoot id="tf">

    <tr>
      <th>
        
      </th>
      <th>
        Итого
      </th>
      <th>
        
      </th>
      <th>
        <span id="kol">0</span>
      </th>
      <th>
        <span id="sum">0.00</span>
      </th>
      <th>
        <input type="button" value="Удалить отмеченные" onclick="RemoveSelected()"/>
      </th>
    </tr>
    
  </tfoot>
</table>
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
<script language="JavaScript">
  var tbl = document.getElementById('tblOrder');
  var oList = document.getElementById('lstProducts');
  var txt = document.getElementById('txtQty');
  var tf = document.getElementById('tf');
  var kol = document.getElementById('kol');
  var sum = document.getElementById('sum');
  



  /* Добавление пунктов заказа */
  function AddToCart() {
  /* Определяем значение, введѐнное в текстовое поле */
  var qty = document.getElementById('txtQty').value;
  /* Проверка: распознаѐтся ли значение как число? Если нет, считаем
  единицей */
  if (parseFloat(qty) != qty)
  qty = 1;
  /* Вставляем строку в тело таблицы */
  var oRow = tbl.tBodies[0].insertRow(-1);
  /* В добавленную строку вставляем, во-первых, checkbox */
  oRow.insertCell(-1).innerHTML = '<input type="checkbox">';
  /* во-вторых, текст, взятый из списка выбора продуктов */
  oRow.insertCell(-1).innerHTML =
  oList.options[oList.selectedIndex].text;
  /* в-третьих, цена выбранного продукта */
  oRow.insertCell(-1).innerHTML = oList.value;
  /* далее, количество, указанное в текстовом поле */
  oRow.insertCell(-1).innerHTML = txt.value;
  /* затем стоимость пункта заказа*/
  oRow.insertCell(-1).innerHTML = txt.value * oList.value;
  /* и, наконец, кнопку "Удалить" */
  oRow.insertCell(-1).innerHTML = '<input type="button" value="Удалить">';

  
  Calculate();

  }
  function Calculate() {
    /* Счётчики для количества единиц товара и общей стоимости */
    var qty = 0, amount = 0;
    /* Цикл по всем строкам в теле таблицы */
    for (var i = 0, n = tbl.tBodies[0].rows.length; i < n; i++) {
      /* Увеличиваем qty на значение в 3 столбце текущей строки */
      qty += parseFloat(tbl.tBodies[0].rows[i].cells[3].innerHTML);
     
      /* Увеличиваем amount на значение в 4 столбце текущей строки */
      amount += parseFloat(tbl.tBodies[0].rows[i].cells[4].innerHTML);
    }
     kol.innerHTML = qty;
     sum.innerHTML = amount;

    /* Записываем qty в 3 столбец нижнего колонтитула */
    
    /* Записываем amount в 4 столбец нижнего колонтитула */
    
  }
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-05-14
@vadikkkxgavrilenko

Invalid html that the browser is trying to correct, resulting in a row with column headers in the tbody, and the text in the headers is processed as part of the data when calculating the sum - hence NaN.
The caption tag must be the first nested element of the table tag, it doesn't belong inside a th.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question