Use javascript to change <td> background colour based on value in an array

Discussion in 'Web Design and Development' started by dom.mason, May 3, 2010.

  1. dom.mason macrumors newbie

    Joined:
    Oct 28, 2009
    #1
    Thank you in advance for any help/suggestions as I am stuck for ideas now.

    What I am trying to do is use javascript to change a tables <td> background colour based on a value in a 2d array.

    This is what i have so far (to create the table). The array will contain a number from 0-7 and starting from the first <td> iterate through and change the colour of the <td> based on the value at the current index of the array. note-the array will be requested from a web service, but for now am happy to use a test array

    I am new to javascript so would greatly appreciate some help.

    Thank you again in advance

    Code:
    <script type="text/javascript" language="javascript">
                ///Create board
                var width = 16;
                var height = 30;
                // currently empty //  var testArray[][] = {};
    
                function createBoard() {
                    var i; //Count variable for height
                    var a; //Count variable for width
                    for (i = 0; i < height; i++) {
                        document.write("<tr id ='" + i + "'>")
                        for (a = 0; a < width; a++) {
                            document.write("<td id='" + a + "'></td>")
                        }
                        document.write("</tr>")
                    }
                }
            </script>
     
  2. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    Untested
    PHP:
    <script type="text/javascript">
    // Create board
    var width 16;
    var 
    height 30;
    // currently empty
    var testArray[][] = {};
    var 
    colors = ['000''f00''0f0''00f''ff0''f0f''0ff'];

    // Fill test array
    for (var a=0a<heighta++)
    {
        for (
    b=0b<widthb++)
        {
            
    testArray[a][b] = Math.floor(Math.random()*7);
        }
    }

    function 
    createBoard() {
        for (
    0heighta++) {
            
    document.write("<tr id ='" "'>")
            for (
    0widthb++) {
                
    document.write("<td id='" a+"_"+"' style='background='"+
                    
    colors[testArray[a][b]] +"'></td>")
            }
            
    document.write("</tr>")
        }
    }
    </script>
     
  3. dom.mason thread starter macrumors newbie

    Joined:
    Oct 28, 2009

Share This Page