I have a simple HTML Form with one column having a select menu with 2 options: Moderate or High. I need to find all rows where the cell = “Moderate” and count the total of another cell in the same row, and repeat this for all rows where the cell = “High”. Here’s a JS Fiddle showing a sample completed table:
In this example the result for Total Moderate would be 1.6 and the result for Total High would be 8.7 (it’s totalling the value in the Average Hours/Week column). The number of rows will not be fixed in advance – there could be 1 or more.
Here’s the actual html for the form:
<div class="span8"><br>
<table id="activities" class="table table-bordered table-striped">
<thead>
<tr>
<th>Activity</th>
<th>Risk</th>
<th>Hours/Week</th>
<th>Weeks/Year</th>
<th>Average Hours/Week</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="Activity" id="Activity" type="text" value=""/></td>
<td><div class="controls">
<select id="Risk">
<option></option>
<option>Moderate</option>
<option>High</option>
</select>
</div></td>
<td><input class="span1" id="A1" type="text" value=""/></td>
<td><input class="span1" id="B1" type="text" value=""/></td>
<td><input class="span1" id="C1" type="text" value=""/></td>
<td><button class="btn">Delete Activity</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Total Moderate</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Total High</td>
<td></td>
</tr>
</tbody>
</table>
</div>
I use jQuery’s
.find()and.each()function to iterate over each row. I usefindagain to find the level and value (2nd and 5th columns) and a switch statement to add the value to the totals. I need to dovalue*1to convert the string to an integer so it will add. Default behavior here is concatenate.The last two lines set the value of the table cells. It’d be a lot easier if you could just give those a specific ID so you can just do
$("moderateTotal").html()but since that wasn’t given I used some jQuery selectors to do it.Demo