Benjamin Lee Benjamin Lee - 2 months ago 6
HTML Question

Multiple <td> with mutiple conditions

I am creating a table looks like this with the codes below:

enter image description here

I am trying to use 'Javascript' to do set condition and compare to value in "td".
I am having problem to set different condition for each column.

Need help:



Eg: I want to set 2 conditions, how do i assign td name/id?


  • [Condition 1] Highlight, if 'Qty' less than '1000'.

  • [Condition 2] Highlight, if 'percentage' less than '80%'.

    <style>
    table, th, td {
    border: 1px solid black;
    }
    </style>
    <script src="js/jquery.min.js"></script>

    <table id='ss'>
    <tr>
    <th>WW</th>
    <th>Qty</th>
    <th>percentage</th>
    </tr>
    <tr>
    <td>WW01</td>
    <td>1000</td>
    <td>50%</td>
    </tr>
    <tr>
    <td>WW02</td>
    <td>2000</td>
    <td>90%</td>
    </tr>
    </table>

    <script>
    $("#ss td").each( function() {
    var thisCell = $(this);
    var cellValue = parseInt(thisCell.text());

    if (!isNaN(cellValue) && (cellValue <=1000)) {
    thisCell.css("background-color","#FFEEC4");
    }
    }
    )
    </script>


Answer

Check my Snippet, based from your example condition:

Eg: I want to set 2 conditions, how do i assign td name/id?

  • [Condition 1] Highlight, if 'Qty' less than '1000'.
  • [Condition 2] Highlight, if 'percentage' less than '80%'.

$('#ss tr').each(function() {
  var that = $(this);
  var c1 = $('td:nth-child(2)', that);
  var c2 = $('td:nth-child(3)', that);
  
  if (parseInt(c1.text()) < 1000)
    c1.css('background-color', '#FFEEC4');
  
  if (parseInt(c2.text()) < 80)
    c2.css('background-color', '#FFEEC4');
});
table, th, td {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='ss'>
  <tr>
    <th>WW</th>
    <th>Qty</th> 
    <th>percentage</th>
  </tr>
  <tr>
    <td>WW01</td>
    <td>1000</td> 
    <td>50%</td>
  </tr>
  <tr>
    <td>WW02</td>
    <td>2000</td> 
    <td>90%</td>
  </tr>
</table>