I am trying to create select
in a list dynamically, I have the values in a array
.
var ruits = ["Banana", "Orange", "Apple", "Mango"];
function AddItem() {
var tbody = null;
var tabla = document.getElementById("tabla");
var nodes = tabla.childNodes;
for (var x = 0; x<nodes.length;x++) {
if (nodes[x].nodeName == 'TBODY') {
tbody = nodes[x];
break;
}
}
if (tbody != null) {
var tr = document.createElement('tr');
tr.innerHTML = `<td>
<select>
<option>Seleccionar</option>
</select>
</td>`;
tbody.appendChild(tr);
}
}
<form>
<table id="tabla">
<thead>
<tr>
<th>Select</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onClick="AddItem();">Agregar item.</button>
</form>
My problem is that the select
dynamically created one has the values of the array. I tried to put it in a foreach but it didn't work for me either.
What I'm trying to do is something like this:
tr.innerHTML = `<td>
<select>
ruits.forEach(function(element) {
<select>${element}</select>
});
</select>
</td>`;
Try this:
There is a simpler way to do this:
tbody
the tableselect
and itsoptions
reading the values of the array with aforEach
insertAdjacentHTML
to create the new rowThis is a much lighter code, since it does not do all the reading of each element of the table to determine the element of the table
tbody
.I hope it helps you