StarCub
StarCub

Reputation: 4341

jQuery AND selector

I have a datagrid(asp.net) on my page. I would like to select all rows that has the word 'foo' in the first column AND the word 'bar' in the second column.

I only know how to do it for the first column.

jQuery('[id$="datagrid1"] tr td:contains(foo)')

Can anyone please let me know how to include the condition for the second column which has the word 'bar'?

Edit: Also, how do I match the word exactly? As selector contains matches when the cell contains the word.

Upvotes: 3

Views: 510

Answers (3)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

Like this:

jQuery('[id$="datagrid1"] tr').filter(function(){
   var $tds = $(this).find("td");
   return ($tds.eq(0).text()=="foo" && $tds.eq(1).text()=="bar");
});

The same code more 'explained'

$trs = jQuery('[id$="datagrid1"] tr').filter(function(){
   var $first_td = $(this).find("td").eq(0);  //First column
   var $second_td = $(this).find("td").eq(1); //Second column
   return ($first_td.text()=="foo" && $second_td.text()=="bar"); //Condition to filter
});

This returns a set of <tr> that match the condition you want.

Hope this helps. Cheers

Upvotes: 3

David Tang
David Tang

Reputation: 93664

Selectors only get you so far. Use .filter() for greatest flexibility:

jQuery('[id$="datagrid1"] tr').filter(function () {
    return $('td:eq(0)', this).text() == 'foo' &&
        $('td:eq(1)', this).text() == 'bar';
});
  • The .filter() functions iterates through each element and expects you to return true or false to indicate whether the element should be kept (matches).
  • The :eq() selector lets you choose an index within the matched set.

Upvotes: 6

jerluc
jerluc

Reputation: 4316

You can use the next-sibling selector assuming the second column <td> is adjacent to the first column <td>

Upvotes: 2

Related Questions