Derreck Derreck - 4 months ago 8
Javascript Question

How can I Use a javascript for loop to create a table with multiple rows?

I want to make a table of colors with eight rows using a javascript for loop. I did this with php and mysql but I can't seem to figure out how to output the and tags to create the distinct rows. So far this is what I have (The table has an id="colorpicker"):

<script type="text/javascript">

var colors = ['000033', '000066', '000099', '0000CC', '0000FF', '003300', '003333', '003366', '003399', '0033CC', '0033FF', '006600', '006633', '006666', '006699', '0066CC'];
var i = 0;
var len = colors.length;
var colorpicker = "";
var a = colors.indexOf('i');

for (i = 0; i < len; i++) {

colorpicker += "<tr><td style='color:#"+colors[i]+"'>"+colors[i] +"</td> </tr>";
}

document.getElementById("colorpicker").innerHTML = colorpicker;

</script>


What I think I need to do is determine the index of the colors and then use modular division to determine whether the index % 8 === 0. This is what I tried that didn't work:

var colors = ['000033', '000066', '000099', '0000CC', '0000FF', '003300', '003333', '003366', '003399', '0033CC', '0033FF', '006600', '006633', '006666', '006699', '0066CC'];
var i = 0;
var len = colors.length;
var colorpicker = "";
var a = colors.indexOf('000033');
var b = colors.indexOf('003399');

for (i = 0; i < len; i++) {

if(a % 8 === 0){

// begin row
colorpicker += "<tr><td style='color:#"+colors[i]+"'>"+colors[i] +"</td>";
}else if((b) % 8 === 0){
// end row
colorpicker += "<td style='color:#"+colors[i]+"'>"+colors[i] +"</td></tr>"
}else{
// midle of row
colorpicker += "<td style='color:#"+colors[i]+"'>"+colors[i] +"</td> ";
}


}

document.getElementById("colorpicker").innerHTML = colorpicker;


The above will still result in a new row for each color.
Any help will be greatly appreciated.

Answer

https://jsfiddle.net/ozhxzoph/

Is that what you meant to do? If so, you need to change "color" to "background-color".

Change this:

colorpicker += "<tr><td style='color:#"+colors[i]+"'>"+colors[i] +"</td>  </tr>";
}

To this:

colorpicker += "<tr><td style='background-color:#"+colors[i]+"'>"+colors[i] +"</td>  </tr>";
}

OR do you mean you want something like this? Where its a sort of grid of colors? The only difference here being that these are columns of 8, as opposed to rows of 8 which you seemed to be asking for.

https://jsfiddle.net/ozhxzoph/1/

Double Edit. Here is the solution for having 8 columns instead of 8 rows. The code has changed slightly more here though. Was a fun problem. :)

https://jsfiddle.net/ozhxzoph/2/

Hope this helps.