Stig Perez
Stig Perez

Reputation: 3853

select last elements from parents

I'm quite new to JQuery so this is probably an easy one...

Consider this HTML structure - I know it is not valid HTML but that's not the point:

<table id="mytable">
<tr>
    <td><input type="checkbox" checked="checked" /></td>
    <td>1.2</td>
    <td>1.3</td>
</tr>
<tr>
    <td><input type="checkbox" checked="checked" /></td>
    <td>2.2</td>
    <td>2.3</td>
</tr>
<tr>
    <td><input type="checkbox" /></td>
    <td>3.2</td>
    <td>3.3</td>
</tr>
</table>

Basically I need to select the last table cell from each table row where the checkbox is marked, in this case the table cells containing "1.3" and "2.3" (not "3.3"). Finding the checked checkboxes is easy but somehow I always end up with only the last table cell ("2.3") from the last table row. Does someone know a solution to this?

Upvotes: 0

Views: 120

Answers (3)

JAstanton
JAstanton

Reputation: 87

There could be an easier way to do this but this is my solution:

$("#mytable td input:checked")
    .parent().parent()
    .find("td:last")
    .css("color","red");​

To see a working example: http://jsfiddle.net/exQZJ/

Upvotes: 0

bondythegreat
bondythegreat

Reputation: 1409

var result;

$('#mytable tr').each(function() {
    if ($(this).find('input').attr('checked') == 'checked') {           
        result = $(this).children('td:last-child').html();
        alert(result);
    }       
})

Upvotes: 0

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

Something like this perhaps:

var foo = $('#mytable tr:has("input:checked") td:last-child');

Upvotes: 2

Related Questions