Question : Loop code to dynamically build HTML table

I would like to create a loop instead of repeating the blocks of code shown below.

Can someone show me how to use the loop index in the variable names and cell indices?

Thanks.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
var cell1 = row.insertCell(0);
	var element1 = document.createElement("img");
	element1.src = imagePath + "1_tn.jpg";
	cell1.appendChild(element1);

	var cell2 = row.insertCell(1);
	var element2 = document.createElement("img");
	element2.src = imagePath + "2_tn.jpg";
	cell2.appendChild(element2);

	var cell3 = row.insertCell(2);
	var element3 = document.createElement("img");
	element3.src = imagePath + "3_tn.jpg";
	cell3.appendChild(element3);

	var cell4 = row.insertCell(3);
	var element4 = document.createElement("img");
	element4.src = imagePath + "4_tn.jpg";
	cell4.appendChild(element4);

        --ETC--

Answer : Loop code to dynamically build HTML table

try using an array for the variables

var cells = new Array();
var elements = new Array();

run a for loop to run it as many times you want

for(i=0;i<NUMBER_REQUIRED;i==0{
cells[i] = row.insertCell(0);
elements[i] = document.createElement("img");
      elements[i].src = imagePath + (i+1)+"_tn.jpg";//since i starts from 0 and you require 1, hence (i+1);
      cells[i].appendChild(elements[i]);

}

hope this helps
Random Solutions  
 
programming4us programming4us