flish
flish

Reputation: 596

jquery retrieve ids of some elements and write them in an array

I need to do the following: check if the 3rd td of a tr contains (exactly) 56 and then retrieve the id of the checkbox contained in the first td of that row.

<table>
    <tr class="bg">
        <td nowrap="nowrap">
            <input class="selected_ads" type="checkbox" id="43617" />
        </td>
        <td class="pa">text text</td>
        <td class="pa">56</td>
    </tr>
    <tr class="bgwhite">
        <td nowrap="nowrap">
            <input class="selected_ads" type="checkbox" id="183578" />
        </td>
        <td class="pa">text</td>
        <td class="pa">56</td>
    </tr>
</table>

($(".bg td:nth-child(3):contains('56')").length>0) or ($(".bgwhite td:nth-child(3):contains('56')").length>0) checks if the third cell contains the value I am looking for.

$(".pa").siblings().first().children("input[type='checkbox']") gets me the checkbox, but I cannot retrieve its id.

Ideally my code would look like this:

var longlist = [];
for each ($(".bg td:nth-child(3):contains('56')").length>0) {

retrieve the id of $(".pa").siblings().first().children("input[type='checkbox']");
longlist.push(checkbox_id);
}

do the same for .bgwhite;

Ideally it would work too.

The most important thing for me would be to retrieve the id.

Upvotes: 0

Views: 100

Answers (2)

Johan
Johan

Reputation: 35194

$('.bg .pa:last').each(function(){

     if($(this).text() === '56'){

         longlist.push( $(this)
                           .closest('.bg')
                           .find('.selected_ads')
                           .attr('id') );
     }
});

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

Given a jQuery element:

var $foo = $(".pa").siblings().first().children("input[type='checkbox']");

There are at least 4 ways to access its ID:

  1. var id = $foo[0].id; – array dereferencing + vanilla DOM
  2. var id = $foo.get(0).id;http://api.jquery.com/get + vanilla DOM
  3. var id = $foo.attr('id');http://api.jquery.com/attr
  4. var id = $foo.prop('id');http://api.jquery.com/prop

Are you saying that you tried all of those and none worked?

Upvotes: 1

Related Questions