php - How to change the background color of a cell based on its value using javascript? -


i have table 3 columns:

  • field1 category
  • field2 , field3 hold measures (integers 1,2,3,4 , 5 exact).

using javascript, how can conditionally format background color of cells in table hold these measures (notably field2 , field3) correspond following colors:

  • cells 1 red
  • cells 2,3, , 4 blue
  • cells 5 green

here's have far (it's in 1 html file now, while sorted out) , i've broken readability. think might missing background attribute in html altogether. know possible, not sure how dynamically change background color of table cell depending on contents using javascript.

thanks in advance.

start of script

<html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script> <script type="text/javascript">  $(document).ready(function(){     $( "#status_report td.measure:contains('1')" ).css('background-color', '#fcc' ); }); </script> <style type="text/css"> </style> </head> <body> <table id="status_report"> <tr>     <th>field1</th>     <th>field2</th>     <th>field3</th> </tr> <tr>     <td class = "measure">example</td>     <td class = "measure">1</td>     <td class = "measure">2</td>     </tr> </table> </body> </html> 

update:

a comment pointed out syntax error (extra semi-colon) removed , above code works fine. however, there better answer posted , has been accepted.

you php. why? because js executed on client-side , if turned off, users not see colored cells.

<?php  $colors = array(   1 => "red",   2 => "blue",   3 => "blue",   4 => "blue"   5 => "green" ) ;  foreach( $data $row ) : ?> <tr>   <?php foreach($row $num): ?>     <td style="background-color: <?php echo (isset($colors[(int)$num]) ? $colors[(int)$num] : "white") ; ?>"><?php echo $num ; ?></td>   <?php endforeach ; ?> </tr>    <? endforeach; ?> 

you use classes in td tags instead of straight style.

if still need solution jquery, can edit answer.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -