Td color according to value

0

I have an HTML table with two columns (description and value), and I need each row to paint a specific color depending on the value of the "value" column.

With jQuery I am using this:

$("#mitabla td:last-child:contains(5)")
    .parents("tr")
    .css("background-color", "verde");

but if I do the same for each value (the possible values are known, only numbers between 1-10) it does not work, and only colors according to the first condition that I have written.

How can this be done, with some if or switch ?

    
asked by daniel2017- 17.07.2017 в 18:59
source

2 answers

1

One way to fix it could be the following:

  • Define each rule that applies to each case ( valor 1, 2, 3, etc. )
  • [Optional] If the rows are loaded dynamically, you should move these rules to a function ( ejemplo: colorearFilas ) and execute that function each time the table is updated.

Example:

$(function() {
  $('#table td:last-child:contains(1)').closest('tr').css('background-color', 'red');
  $('#table td:last-child:contains(2)').closest('tr').css('background-color', 'blue');
  $('#table td:last-child:contains(3)').closest('tr').css('background-color', 'green');
  // Así sucesivamente hasta llegar al 10
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table">
  <thead>
    <tr>
      <th>Descripción</th>
      <th>Valor</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Algo 1</td>
      <td>1</td>
    </tr>
    <tr>
      <td>Algo 2</td>
      <td>2</td>
    </tr>
    <tr>
      <td>Algo 3</td>
      <td>1</td>
    </tr>
    <tr>
      <td>Algo 4</td>
      <td>3</td>
    </tr>
    <tr>
      <td>Algo 5</td>
      <td>1</td>
    </tr>
  </tbody>
</table>
    
answered by 17.07.2017 / 19:47
source
0

Once you load the page, the table changes its value?

If the answer is no, you could use something like this:

<script type="text/javascript">
$( document ).ready( function() {
$( "#tiobeTable tbody tr td.ratings" ).each( function( index ) {
if ( parseFloat( $( this ).text() ) > 10 ) {
$( this ).addClass( "highlight" );
}
});
$( "#tiobeTable tbody tr td.delta" ).each( function( index ) {
if ( parseFloat( $( this ).text() ) < 0 ) {
$( this ).addClass( "highlight-negative" );
}
});
});
</script>

If you do not understand, let me know and I'll explain it better. I pass the link where you take it out, which has more info that may be useful. Greetings.

link

    
answered by 17.07.2017 в 19:40