I have an html table and I'm trying to create n number of rows using pure JavaScript, and populate the table using JSON data (I've created a variable with JSON data in it within the JavaScript code). The problem is, nothing happens when I click the button; the rows don't get created. For testing purposes, I tried adding a <p> element and some JavaScript to alter that element like this:
document.getElementById("test").innerHTML="TEST";
And that works so I know that there's something wrong with the code that inserts rows and the data.
Here is my code:
function populate() {
var rows = [{
"ID": "John",
"LastName": "Test",
"DOB": "03-12-1959",
"Gender": "M"
},
{
"ID": "John",
"LastName": "Test",
"DOB": "03-12-1959",
"Gender": "M"
}
];
var colNum = rows[0].length;
var testtable = document.getElementsByClassName("test-table");
for (var i = 0; i <= rows.length; i++) {
var testrow = testtable.insertRow();
for (var j = 0; j <= colNum; j++) {
var testcells = testrow.insertCell();
testcells.innerHTML = rows[i][j];
}
}
}
<button onclick="populate()">Test</button>
<table class="test-table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<label for="row1"></label>123</td>
<td>John</td>
<td>Doe</td>
<td>02-15-1982</td>
<td>M</td>
</tr>
<tr>
<td colspan="6">
<input id="row1" type="checkbox">
<table>
<tr>
<th>Phone Number</th>
<td>555-3226</td>
<th>City:</th>
<td>New York</td>
</tr>
<tr>
<th>Hire Date:</th>
<td>8/13/12</td>
<th>Salary:</th>
<td>$48,000</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
When I inspect element in the browser (firefox) it tells me that 'insertRow' is not a function.
Is there another way to do this? How can I fix this? Any help would be appreciated.