Table coloring

Discussion in 'HTML & Website Design' started by gudzik, Mar 2, 2012.

  1. #1
    How to fill in a cell of the table with color depending on value?
     
    gudzik, Mar 2, 2012 IP
  2. CIScripts

    CIScripts Member

    Messages:
    44
    Likes Received:
    2
    Best Answers:
    2
    Trophy Points:
    30
    #2
    There are multiple ways of doing this by making changes in the frontend or backend. If you're the coder of the backend, or able to modify it, I'd suggest you do this there, by using something like this (just a sample code, you need to adapt it to your needs):

    <?php
    if($cell_value > 0 && $cell_value <= 10)
    {
        echo '<td style="background:green;">' . $cell_value . '</td>';
    }
    else if($cell_value > 10 && $cell_value <= 100)
    {
        echo '<td style="background:yellow;">' . $cell_value . '</td>';
    }
    else if($cell_value > 100 && $cell_value <= 1000)
    {
        echo '<td style="background:red;">' . $cell_value . '</td>';
    }
    // ...
    // etc
    // ...
    ?>
    PHP:
    Otherwise a frontend-solution using jQuery would look something like this:

    
    $('table td').each(function() {
        var cell_value = $(this).html();
        if(cell_value == 'desired value') {
            $(this).attr('style', 'background:red');
        }
        // ...
        // etc
        // ...
    });
    
    Code (markup):
    Hope this helps :)
     
    CIScripts, Mar 2, 2012 IP
  3. SoftCloud

    SoftCloud Well-Known Member

    Messages:
    1,060
    Likes Received:
    28
    Best Answers:
    2
    Trophy Points:
    120
    #3
    If you're using a normal table then you can either "hard code" the color into the cell's <td> tag...
    <td bgcolor="#FF9900">some text</td>
    Code (markup):
    ^ That will make it orange, OR you can use CSS
    <style type="text/css">
    .mycell {
    background: #FF9900;
    }
    </style>
    *snip*
    <td class="mycell">some text</td>
    *snip*
    Code (markup):
    I hope that helps. :)
     
    SoftCloud, Mar 2, 2012 IP
  4. gudzik

    gudzik Member

    Messages:
    44
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #4
    At me the table is formed sql-inquiry and has many values. I need to paint it automatically.
    I will try to adapt the first way.
     
    gudzik, Mar 2, 2012 IP
  5. CIScripts

    CIScripts Member

    Messages:
    44
    Likes Received:
    2
    Best Answers:
    2
    Trophy Points:
    30
    #5
    Yes, that's the best way, I forgot to mention that the first way is better because it's not slowing down your user's browser, especially if your tables are heavy.
     
    CIScripts, Mar 2, 2012 IP