SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jul 2012
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Exclamation adding conditional background color using javascript

    Hi All,

    I am pretty new to JS so forgive me if I am lame.
    The issue:

    I have a Javascript where I am storing all the data of a table in an array (say list_array)
    eg.
    for (i=1; i<row_count;i++) //Loop through the rows. Skipping header row and starting from 1
    {
    column = rows[i].getElementsByTagName("td");
    var list_row_array = new Array(); // Create child array. Each element of this array represents a column on the row.
    for(j=0;j<column_count;j++) // Loop through the columns for each row
    {
    // Read value from the cell and store it in array
    list_row_array[column_names[j]] = column[j].getElementsByTagName("span")[0].innerHTML;
    }
    list_array[i-1] = list_row_array;
    }




    1. I have 4 distinct values in column #4. say A, B, C &D
    2. I wish to color the rows in based on value in column #4. eg. if A then blue, B then red, C then black and D then white
    3. And I have to use the array in the JS only.
    Please suggest any method.

    Thanks and Regards,
    AvantA

  2. #2
    Non-Member
    Join Date
    Jul 2012
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here is a quick and simple way to get you started. You don't need arrays at all.

    Code:
        <body>
            <table cellpadding="10" cellspacing="0">
                <tbody id="tby1">
                    <tr>
                        <td>11</td><td>22</td><td>33</td><td>A</td>
                    </tr>
                    <tr>
                        <td>11</td><td>22</td><td>33</td><td>B</td>
                    </tr>
                </tbody>
            </table>
            <script type="text/javascript">
                var oTby1 = document.getElementById('tby1');
                for(i=0; i<oTby1.rows.length; i++){
                    switch(oTby1.rows[i].cells[oTby1.rows[i].cells.length-1].innerHTML.toLowerCase()) {
                        case 'a':
                            bgColor = 'red';
                            break;
                        case 'b':
                            bgColor = 'green';
                            break;
                        default:
                            bgColor='white';
                    }
                    oTby1.rows[i].style.backgroundColor = bgColor;
                }
            </script>
        </body>
    You can add the extra rows in the table and code for extra colours.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •