Reputation: 552
Let's say i have a table like this:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="selection">
<th>Values</th>
<th>Average</th>
<tbody>
<tr>
<td>5</td>
<td></td>
</tr>
<tr>
<td>0.9</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>6</td>
<td></td>
</tr>
</tbody>
</table>
I want to calculate average of column "values" and put it in each td of the average column using Jquery. The result shoud be like this picture:
Please note that i filter results in the table with a search box and the number of rows will change each time the user searches.
Upvotes: 0
Views: 7451
Reputation: 87083
var sum = 0,
count = -1,
all = $('#selection > tbody > tr');
all.each(function() {
sum += +$('td:eq(0)', this).text();
count++;
});
all.find('td:eq(1)').text((sum / count).toFixed(3));
+$('td:eq(0)', this).text()
, here the beginning +
sing convert the text to number.
Upvotes: 3
Reputation: 160903
var sum = 0, rows = $('#selection tbody tr');
rows.each(function() {
sum += parseFloat($(this).children('td').eq(0).text());
});
rows.each(function() {
var tds = $(this).children('td'), value = parseFloat(tds.eq(0).text());
$(this).children('td').eq(1).text((value/sum).toFixed(3));
});
Upvotes: 1