Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access nth column of table

Tags:

jquery

I have a table with the following structure and data

<tr>
<td><input id="c1" type="checkbox"/></td>
<td>342</td>
<td>24</td>
<td>Jeff</td>
</tr>
<tr>
<td><input id="c2" type="checkbox"/></td>
<td>343</td>
<td>29</td>
<td>Libo</td>
</tr>

I want to calculate total value of the third column of all rows, which are checked. So assuming both rows above are checked, the value of third column will be 24+29=53

like image 498
Karl Iot Avatar asked Mar 02 '11 09:03

Karl Iot


2 Answers

var total = 0;
$("table tr:has(:checkbox:checked) td:nth-child(3)").each(function() {
    total += parseInt($(this).text());
});

See this fiddle.

like image 52
melhosseiny Avatar answered Oct 15 '22 13:10

melhosseiny


var total = 0;
Array.prototype.slice.call(document.getElementById('tableID').rows).
forEach(function(row) {
    if (!row.childNodes[1].firstChild.checked) return;
    total += parseFloat(row.childNodes[2].innerHTML);
});

The OP asked to count only those that are checked. This answer only counts checked rows.

like image 40
Delan Azabani Avatar answered Oct 15 '22 13:10

Delan Azabani