Skip to content
Advertisement

How do I sum the price column from HTML table using JavaScript?

I am trying to add Price from table column to a total. I am having problem adding values such as 10.00 or 5.99. I am able to calculate prices with int values, but not with values 10.00 or 5.99, etc.

Here is what I have below.

var table = document.getElementById("myTable"),
  sumVal = 0;
for (var i = 1; i < table.rows.length; i++) {
  sumVal = sumVal + parseF(table.rows[i].cells[2].innerHTML);
}

document.getElementById("val").innerHTML = "SubTotal =" + sumVal;
console.log(sumVal);
<table id="myTable">
  <tr>
    <th>Item</th>
    <th>Price</th>
    <th>Remove</th>
  </tr>
  <tr>
    <td>Hoddie</td>
    <td class="count-me">15.00</td>
    <td><button onClick="myFunction()">Remove</button></td>
  </tr>
  <tr>
    <td>Nike Cap</td>
    <td class="count-me">10.99</td>
    <td><button onClick="myFunction()">Remove</button></td>
  </tr>
</table>
<span id="val"></span>

Advertisement

Answer

You have three issues:

  1. You are grabbing the wrong cell index, indices start at 0:
    • table.rows[i].cells[1]
  2. You need to call the correct parse function:
    • parseFloat(table.rows[i].cells[1].innerHTML);
  3. You need to format your output:
    • "SubTotal = $" + sumVal.toFixed(2);

Update: Added functionality for removing rows.

updateSubTotal(); // Initial call

function updateSubTotal() {
  var table = document.getElementById("myTable");
  let subTotal = Array.from(table.rows).slice(1).reduce((total, row) => {
    return total + parseFloat(row.cells[1].innerHTML);
  }, 0);
  document.getElementById("val").innerHTML = "SubTotal = $" + subTotal.toFixed(2);
}

function onClickRemove(deleteButton) {
  let row = deleteButton.parentElement.parentElement;
  row.parentNode.removeChild(row);
  updateSubTotal(); // Call after delete
}
#myTable td {
  padding: 0.25em;
}

#val {
  display: block;
  margin-top: 0.5em;
}
<table id="myTable">
  <tr>
    <th>Item</th>
    <th>Price</th>
    <th>Remove</th>
  </tr>
  <tr>
    <td>Hoodie</td>
    <td class="count-me">15.00</td>
    <td><button onClick="onClickRemove(this)">Remove</button></td>
  </tr>
  <tr>
    <td>Nike Cap</td>
    <td class="count-me">10.99</td>
    <td><button onClick="onClickRemove(this)">Remove</button></td>
  </tr>
</table>
<span id="val"></span>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement