views:

119

answers:

2

I have the following table:

<table class="grid">
    <thead>
     <tr>
      <th>Name</th>
      <th>Status</th>
     <tr>
    </thead>
    <tbody>
     <tr>
      <td>Project 1</td>
      <td>Closed</td>
     <tr>
     <tr>
      <td>Project 2</td>
      <td>Open</td>
     <tr>
     <tr>
      <td>Project 3</td>
      <td>Closed</td>
     <tr>
    </tbody>
</table>

I am trying to move some of my UI code that I used to do in the code-behind to jQuery. I would like to change the class of TR element whenever the Status (Column 2) column has a value of Open.

What would be the best approach to doing this with jQuery?

+4  A: 
$('tbody > tr', 'table.grid').filter(function() {
    return $(this).children('td').eq(1).text() == 'Open';
}).addClass('open_tr');

What it is doing:

It is selecting all the <tr> elements inside the <tbody> of the table.grid context. The filter function allows you to filter elements based on what you return, either true to keep or false to discard. So inside the filter we get all the children of the tr, get the 2nd <td>, and return whether or not its text is equal to 'Open' - if it is, it would return true, and we could keep the parent <tr> in the selector. All that is left would then just be <tr> with Open status, so we can add a class to mark them as such.

Paolo Bergantino
Thanks for the help! Still new to jQuery!
mattruma
you should probably add a "return" somewhere ;)Good one though
Julian Aubourg
Yeah, my bad. I updated it. Should be working now. Tested.
Paolo Bergantino
+1  A: 

I am not writing any code because you could re-use some of the jQuery scripts which allow you to generate alternate colors for table rows - with a little modification.

Basically, on page load (in jQuery terms - on document ready)

  1. get a reference to the table's rows.
  2. iterate through the rows checking for the particular columns' value.
  3. if it matches your requirements, change the row color.
Abhishek