I need to fill in an HTML table from JS (I have just started with JS). Here is my code based on an example I found:
length = Table.length
const Table = document.getElementById("TblBody")
for ( i = 0; i<length; i++ )
{ let row = Table.insertRow();
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell3 = row.insertCell(3);
let cell4 = row.insertCell(4);
cell0.innerHTML = NameTable[i][0];
cell1.innerHTML = NameTable[i][1];
cell3.innerHTML = NameTable[i][2];
cell4.innerHTML = NameTable[i][3];
}
<table id="myTable" border="1" style="display:none; width:500px; float: left">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>....</th>
<th>Phone</th>
<th>Nick Name</th>
</tr>
</thead>
<tbody id="TblBody"></tbody>
</table>
I expected to see about 20 rows of five columns each filled with data.
The results I got with the above code:
the headers displayed as expected
boxes for the first two columns were displayed
neither box had any data
2
Answers
You are trying to use the Table variable before it is defined. You should declare the const Table before using it.
I haven’t tested this code; it would be best if you could show the array with some example data.
do Simply :