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.
JavaScript
x
8
1
var table = document.getElementById("myTable"),
2
sumVal = 0;
3
for (var i = 1; i < table.rows.length; i++) {
4
sumVal = sumVal + parseF(table.rows[i].cells[2].innerHTML);
5
}
6
7
document.getElementById("val").innerHTML = "SubTotal =" + sumVal;
8
console.log(sumVal);
JavaScript
1
18
18
1
<table id="myTable">
2
<tr>
3
<th>Item</th>
4
<th>Price</th>
5
<th>Remove</th>
6
</tr>
7
<tr>
8
<td>Hoddie</td>
9
<td class="count-me">15.00</td>
10
<td><button onClick="myFunction()">Remove</button></td>
11
</tr>
12
<tr>
13
<td>Nike Cap</td>
14
<td class="count-me">10.99</td>
15
<td><button onClick="myFunction()">Remove</button></td>
16
</tr>
17
</table>
18
<span id="val"></span>
Advertisement
Answer
You have three issues:
- You are grabbing the wrong cell index, indices start at 0:
table.rows[i].cells[1]
- You need to call the correct parse function:
parseFloat(table.rows[i].cells[1].innerHTML);
- You need to format your output:
"SubTotal = $" + sumVal.toFixed(2);
Update: Added functionality for removing rows.
JavaScript
1
15
15
1
updateSubTotal(); // Initial call
2
3
function updateSubTotal() {
4
var table = document.getElementById("myTable");
5
let subTotal = Array.from(table.rows).slice(1).reduce((total, row) => {
6
return total + parseFloat(row.cells[1].innerHTML);
7
}, 0);
8
document.getElementById("val").innerHTML = "SubTotal = $" + subTotal.toFixed(2);
9
}
10
11
function onClickRemove(deleteButton) {
12
let row = deleteButton.parentElement.parentElement;
13
row.parentNode.removeChild(row);
14
updateSubTotal(); // Call after delete
15
}
JavaScript
1
8
1
#myTable td {
2
padding: 0.25em;
3
}
4
5
#val {
6
display: block;
7
margin-top: 0.5em;
8
}
JavaScript
1
18
18
1
<table id="myTable">
2
<tr>
3
<th>Item</th>
4
<th>Price</th>
5
<th>Remove</th>
6
</tr>
7
<tr>
8
<td>Hoodie</td>
9
<td class="count-me">15.00</td>
10
<td><button onClick="onClickRemove(this)">Remove</button></td>
11
</tr>
12
<tr>
13
<td>Nike Cap</td>
14
<td class="count-me">10.99</td>
15
<td><button onClick="onClickRemove(this)">Remove</button></td>
16
</tr>
17
</table>
18
<span id="val"></span>