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
jQuery Selectors
jQuery Traversing: Ancestors
jQuery Traversing: Descendants
jQuery Traversing: Siblings
jQuery Traversing: Filtering
Exercises & Assignments
Write jQuery code to count the items of a list
Write jQuery code to find the total of a table column
Write jQuery code to add alternate row colors to a table
Interview Questions & Answers
What are jQuery selectors?
What is the difference between find() and children() in jQuery?
What is the difference between parent(), parents() and closest() in jQuery?
How do you check if an element exists in jQuery?
What is the difference between this and $(this) in jQuery?
What is the use of end() in jQuery?