...">

How can I set the row class of a table based on the content of a cell using jQuery?

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 port a part of my UI code that I used for jQuery code. I would like to change the class of a TR element when the Status (Column 2) is Open.

What would be the best way to do this with jQuery?

0


source to share


2 answers


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

      

What it does:



It selects all <tr>

elements within the <tbody>

context table.grid

. The filter function lets you filter items 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 second one <td>

and return if its text matches "Open", if it does, it will return true and we can store the parent <tr>

in the selector. All that's left will be just <tr>

public, so we can add a class to mark them as such.

+6


source


I am not writing any code because you could reuse some jQuery scripts that will allow you to generate alternate colors for table rows - with a little modification.

Basically, on page load (in jQuery conditions - when the document is ready)



  • get a link to table rows.
  • iterating over the rows, checking the value of a particular column.
  • if it suits your requirement change the line color.
+1


source







All Articles