Karl Iot
Karl Iot

Reputation: 135

Access nth column of table

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

Upvotes: 8

Views: 13983

Answers (4)

belugabob
belugabob

Reputation: 4460

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

Although this may just end up concatenating the text values together, so it might be necessary to coerce the 'text' values into numbers, using parseFloat, as per the other answer.

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

OK, and now to handle the 'checked' part of the requirement (Which I overlooked)

var total = 0;
$("tr td input:checked").closest("tr").find("td:nth-child(3)").each(
    function(){
        total += parseFloat($(this.text()));
    }
);

Upvotes: 1

melhosseiny
melhosseiny

Reputation: 10154

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

See this fiddle.

Upvotes: 15

xkeshav
xkeshav

Reputation: 54050

try this

<script>
        $(document).ready(function(){
          var total = 0;
      $("td:nth-child(3n)").each(
        function(){
            total += parseInt($(this).text());
        }         
        );
         alert(total);
        });
</script>

Upvotes: 0

Delan Azabani
Delan Azabani

Reputation: 81472

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.

Upvotes: 2

Related Questions