Write jQuery code to find the total of a table column
Description: Add all prices of the table and show the total in the last row.
Hint:
- Use
.each(),parseFloat()and the.text()method.
HTML of the page
<table id="cart">
<tr><td>Pen</td><td class="price">10</td></tr>
<tr><td>Notebook</td><td class="price">45.50</td></tr>
<tr><td>Eraser</td><td class="price">5</td></tr>
<tr><td>Total</td><td id="total"></td></tr>
</table>
Solution
var total = 0;
$('#cart .price').each(function () {
total += parseFloat($(this).text());
});
$('#total').text(total.toFixed(2));
console.log('Total = ' + total);
Console output
Total = 60.5
HTML after the code runs
<td id="total">60.50</td>
How it works
each()runs for every price cell, and we add the number to the total.toFixed(2)shows two digits after the decimal point.
Read jQuery each().
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |