Change color of a table row according to the value of td with jquery

Asked

Viewed 1,441 times

1

Good afternoon to you all! I have a table with this information:

<tr>
   <td>Origem</td>
   <td>Destino</td>
   <td>Status</td>
</tr>
<tr class="status" data-status="<?php echo $linha['status'];?>">
   <td>SP</td>
   <td>MG</td>
   <td>C</td>
</tr>

In jquery, I have a code that returns the values like this:

(5) ["M", "C", "C", "C", "C"]

What I need is that when the value of the "status" column is "M", the row has a color and when the value of the "status" column is "C", the row has another color.

My code is like this, but with this code all the lines are one color.

var status = new Array();
        $('.status').each( function( i ){
            var $this = $( this )
            status[i] = $this.attr('data-status');
            if(status[i] == "M"){
                $('.status').addClass('livre');
            }else if(status[i] == "C"){
                $('.status').removeClass('livre').addClass('ocupado');
            }
        });
        console.log(status);

Someone can help in this case?

Thank you very much!

2 answers

0

If the status information is not changing you can put it right in the same class:

<tr class="status status-<?php echo $linha['status'];?>">

There in css you make the rules for each status:

.status-C td {color: red;}
.status-M td {color: green;}

0


Have some problems in your code:

first. Do not use the word "status" to create an array. This word is reserved. When using it, your array will behave like a string. You can add a _ to differentiate it.

2nd. In the if you are calling the element by class (ex., $('.status').addClass('livre');) and not by the loop item.

The right thing would be:

var status_ = new Array('M','C','C','C','C');

$('.status').each( function( i,v ){
   var $this = $( this );
   status_[i] = $this.attr('data-status');
   if(status_[i] == "M"){
       $this.addClass('livre');
   }else if(status_[i] == "C"){
       $this.removeClass('livre').addClass('ocupado');
   }
});
.livre{
   background: yellow;
}

.ocupado{
   background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
   <td>Origem</td>
   <td>Destino</td>
   <td>Status</td>
</tr>
<tr class="status" data-status="M">
   <td>SP</td>
   <td>MG</td>
   <td>C</td>
</tr>
<tr>
   <td>Origem</td>
   <td>Destino</td>
   <td>Status</td>
</tr>
<tr class="status" data-status="C">
   <td>SP</td>
   <td>MG</td>
   <td>C</td>
</tr>
<tr>
   <td>Origem</td>
   <td>Destino</td>
   <td>Status</td>
</tr>
<tr class="status" data-status="M">
   <td>SP</td>
   <td>MG</td>
   <td>C</td>
</tr>
</table>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.