Suduwudu
Suduwudu

Reputation: 29

Set text color column based on value jquery

I have a table and my last column has the value 'Closed' or 'Open'. When the value is Closed I want the text to be red, if it is open it has to be green. But al my values are green.

This is what I have.

var rowCount = $('#ir_doors tr').length;

for (i = 1; i <= rowCount; i++) { 
    if ($( "table tr:nth-child(" + i + ") td:nth-child(5)" ).val() == 'Closed') {
            $( "table tr:nth-child(" + i + ") td:nth-child(5)" ).css("color", "red");
    }
    else {
            $( "table tr:nth-child(" + i + ") td:nth-child(5)" ).css("color", "green");
    }
}

Anybody know what I do wrong?

Thanks.

Upvotes: 0

Views: 157

Answers (3)

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

val() is for inputs. text() is probably what you are going for:

if ($( "table tr:nth-child(" + i + ") td:nth-child(5)" ).text() == 'Closed') {

Upvotes: 1

Tree Frog
Tree Frog

Reputation: 666

val() is used to query the value of elements such as text, select, etc. If you are targeting the contents of a TD, then you'll need to use either html() or text()

Upvotes: 1

Danny
Danny

Reputation: 100

var rowCount = $('#ir_doors tr').length;

    for (i = 1; i <= 2; i++) {
       if ($("table tr:nth-child(" + i + ") td:nth-child(5)").text() == 'Closed') {
            $("table tr:nth-child(" + i + ") td:nth-child(5)").css("color", "red");
       } else {
            $("table tr:nth-child(" + i + ") td:nth-child(5)").css("color", "green");
        }
 }

<table id="ir_doors">
 <tr>
     <td>1</td>
     <td>r2</td>
     <td>3</td>
     <td>4</td>
     <td>Closed</td>
 </tr>
 <tr>
     <td>1</td>
     <td>2</td>
     <td>3</td>
     <td>4</td>
     <td>r2-5</td>
   </tr>

jsFiddle

Upvotes: 1

Related Questions