Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: How to select rows from a table

I have a scenario where I would like to select rows from a table depending upon the values in td

e.g. I have a table like this

<tr>
   <td>John</td>
   <td>Smith</td>
   <td>Male</td>
</tr>
<tr>
   <td>Andy</td>
   <td>Gates</td>
   <td>Male</td>
</tr>
<tr>
   <td>Alice</td>
   <td>Nixon</td>
   <td>Female</td>
</tr>

now I would like to select all the rows if the value of first td is x AND value of second td is y

At the momemnt I am doing something like this

$("tr").each(function (index) {
   if ($(this).find('td:eq(0)').text().trim() == x &&
       $(this).find('td:eq(1)').text().trim() == y)
          ...do somethin....
}); 

looping through each row and check. This is verbose. Is there a better way to achieve this in a single line. I can't seem to figure out AND operator logic with selectors?

Awaiting,

like image 397
nabeelfarid Avatar asked Dec 29 '22 08:12

nabeelfarid


2 Answers

$("tr").each(function (index) {
   if ($.trim($(this).find('td:eq(0)').text()) == x &&
       $.trim($(this).find('td:eq(1)').text()) == y) {
       $(this).closest('table').css('border', '1px solid red');​ // this should do it
   }
}); 

Alternatively, using .filter:

$("tr").filter(function() {
    return $.trim($(this).find('td:eq(0)').text()) == 'John' &&
           $.trim($(this).find('td:eq(1)').text()) == 'Smith';
}).closest('table').find('tr').css('border', '1px solid red');​

Demo: http://jsfiddle.net/WhFbE/5/

like image 139
karim79 Avatar answered Jan 19 '23 03:01

karim79


Here's a selector that should work:

Try it out: http://jsfiddle.net/N6TdM/

var x = "Andy";
var y = "Gates";

var res = $("td:first-child:contains(" + x + ") + td:contains(" + y + ")");

Note that this could fail if you have something like the following:

FIRST:   Roberto       Rob
SECOND:  Robertson     Roberts

Searching for "Rob Roberts" would give two matches.

like image 28
user113716 Avatar answered Jan 19 '23 01:01

user113716