Как мне суммировать все столбцы в таблице с одинаковым именем класса в JavaScript?

#javascript #jquery

#javascript #jquery

Вопрос:

Я пытаюсь суммировать цену в таблице, все цены в <td> имеют одинаковое имя класса, и я хотел бы суммировать их по нажатию кнопки. В конечном итоге я хотел бы также рассчитать количество в сумме. Это то, что у меня есть до сих пор:

 function sumAmounts() {
  var sum = 0;
  var listPriceTotal = $('.txtListPrice').each(function() {
    sum  = parseFloat($(this).html); // Or this.innerHTML, this.innerText
  });
  document.getElementById("txtTotal").value = listPriceTotal;
}

document.getElementById("addTotals").addEventListener("click", () => {
  sumAmounts();


}); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
  <tr>
    <th><label>SKU</label></th>
    <th><label>Retail Price</label></th>
    <th><label>List Price</label></th>
    <th><label>Product Name</label></th>
    <th><label>Quantity</label></th>
  </tr>
  <tr>
    <td class="txtSKU">1234</td>
    <td class="txtRetailPrice">12.50</td>
    <td class="txtListPrice">11.75</td>
    <td class="txtProductName">product 1</td>
    <td class="txtQuantity"><input type="text"> </td>
  </tr>
  <tr>
    <td class="txtSKU">12222</td>
    <td class="txtRetailPrice">14.50</td>
    <td class="txtListPrice">9.75</td>
    <td class="txtProductName">product 2</td>
    <td class="txtQuantity"><input type="text"> </td>
  </tr>
  <tfoot>
    <th><label id="lblTotal">Total:</label><input type="text" name="txtTotal" id="txtTotal">
      <input type="button" value="Add" id="addTotals">
    </th>
  </tfoot>
</table> 

Комментарии:

1. .html должно быть .html() так, как это функция. Но другие варианты в комментарии также будут работать. Итак… В чем проблема?

Ответ №1:

В вашем коде есть две проблемы. Во-первых, вы пытаетесь установить объект jQuery в качестве значения input , которое именно поэтому вы видите [Object object] в поле. Вам нужно установить значение sum равным .

Вторая проблема заключается в том, что вы предоставляете html ссылку на метод parseFloat() , а не фактическое html() значение. С обоими из них код работает:

 function sumAmounts() {
  var sum = 0;
  $('.txtListPrice').each(function() {
    sum  = parseFloat($(this).html());
  });
  document.getElementById("txtTotal").value = sum;
}

document.getElementById("addTotals").addEventListener("click", () => {
  sumAmounts();
}); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
  <tr>
    <th><label>SKU</label></th>
    <th><label>Retail Price</label></th>
    <th><label>List Price</label></th>
    <th><label>Product Name</label></th>
    <th><label>Quantity</label></th>
  </tr>
  <tr>
    <td class="txtSKU">1234</td>
    <td class="txtRetailPrice">12.50</td>
    <td class="txtListPrice">11.75</td>
    <td class="txtProductName">product 1</td>
    <td class="txtQuantity"><input type="text"> </td>
  </tr>
  <tr>
    <td class="txtSKU">12222</td>
    <td class="txtRetailPrice">14.50</td>
    <td class="txtListPrice">9.75</td>
    <td class="txtProductName">product 2</td>
    <td class="txtQuantity"><input type="text"> </td>
  </tr>
  <tfoot>
    <th>
      <label id="lblTotal">Total:</label>
      <input type="text" name="txtTotal" id="txtTotal">
      <input type="button" value="Add" id="addTotals">
    </th>
  </tfoot>
</table>