I need to create a table using only JavaScript. The table is created dynamically so I can add extra rows if I needed too. However, each row on the table needs to have a text box.
When I try to do it this way (shown below) the table loads but says [object HTML Input Element] where the text box should be. I think it's because element.innerHTML is trying to change it to a string.
Can anyone help with another way to add the text box to the table?
for (var i = 0; i < tableRows.length; i++) {
var table = document.getElementById("myTable");
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
//element from array
//input box
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
cell1.innerHTML = "object.Section"; //adds content from array outside the loop
cell2.innerHTML = document.body.appendChild(x); //adding text box
}
Instead of using innerHTML, use appendChild directly on cell2 like this: cell2.appendChild(x);
So, your code will be:
for (var i = 0; i < tableRows.length; i++) {
var table = document.getElementById("myTable");
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
//element from array
//input box
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
cell1.innerHTML = "object.Section"; //adds content from array outside the loop
cell2.appendChild(x); //adding text box
}