Jason McKindly Jason McKindly - 1 year ago 87
jQuery Question

jquery loop table while adding up values

I have the following table which gets populated by php and contains values in the "Calories", "Protein", "Carbs", and "Fats" columns. I am trying to write a jquery script which will iterate through the table and total all the calorie values, protein values, carbs values, and fats values. I am very new to jquery, so I'm having a bit of a rough time. Here's the structure:

<table id="planner_table" class="display">
<thead class="planner_table_head">
<th class="planner_th">Meal Name</td>

<th class="planner_th">Calories</th>

<th class="planner_th">Protein</th>

<th class="planner_th">Carbs</th>

<th class="planner_th">Fats</th>

<?php $dao->fillPlanner($_SESSION['user_id']); ?>

these are what the entries look like which are generated by the PHP:

echo '<tr>';
echo '<td class="centered">' . content . '</td>';
echo '<td class="centered cals">' . content . '</td>';
echo '<td class="centered prot">' . content . '</td>';
echo '<td class="centered carbs">' . content . '</td>';
echo '<td class="centered fats">' . content . '</td>';
echo '</tr>';

any help is appreciated. Thanks

Answer Source

To total the number of calories in the calories column, do this:

var totalCals = 0;

    totalCals += parseInt($(this).html(), 10);

This assumes the only content within each is just the number to be added.

You can do the same for the other column types as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download