Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

dom.mason

macrumors newbie
Original poster
Oct 28, 2009
17
0
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>
 
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=0; a<height; a++)
{
	for (b=0; b<width; b++)
	{
		testArray[a][b] = Math.floor(Math.random()*7);
	}
}

function createBoard() {
	for (a = 0; a < height; a++) {
		document.write("<tr id ='" + a + "'>")
		for (b = 0; b < width; b++) {
			document.write("<td id='" + a+"_"+b + "' style='background='"+
				colors[testArray[a][b]] +"'></td>")
		}
		document.write("</tr>")
	}
}
</script>
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.