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

1

Good afternoon everyone! 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 status column value is "M", the line has a color and when the status column value is "C", the line 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);

Can anyone help in this case?

Thank you!

    
asked by anonymous 28.01.2018 / 17:13

2 answers

0

You have some problems with your code:

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

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

The correct one 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><trclass="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>
    
28.01.2018 / 20:39
0

If the status information does not change you can put it directly into the same class:

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

Then in css you make the rules for each status:

.status-C td {color: red;}
.status-M td {color: green;}
    
28.01.2018 / 17:39