Arkhall Arkhall - 2 months ago 20
HTML Question

Javascript - Create element select from input

I am learning using the events via "nodes" system. But I always have problems with select and options item. The code is good, it works on my local dev. Unfortunately, I had some bugs in JsFiddle =(

Here is the situation.

We have an input, when I type (3 for exemple) and click to "add", I have two inputs (name + surname) that appears for 3 persons in the div "childrenContainer".

Here is the HTML

<label for="nbEnfants">Number : </label>
<input type="text" id="nbEnfants">
<button id="addChildren">Add</button>
<div id="childrenContainer">

Here is the Javascript

var nbEnfants = document.getElementById("nbEnfants").value;
var childrenContainer = document.getElementById("childrenContainer");

for(var i=0; i<nbEnfants; i++){

//First added Input
childrenContainer.appendChild(document.createTextNode("Name : " + (i+1) + " "));
var input = document.createElement("input");
input.setAttribute('type', 'text');

//Second input
childrenContainer.appendChild(document.createTextNode("Surname : " + (i+1) + " "));
var input2 = document.createElement("input");
input2.setAttribute('type', 'text');



This code is good, but I need to add a drop down (select options) for the age of children (1 to 12). Adding inputs is good for me, but adding a select is a little difficult, because I need another loop into this one for adding the age for each children.

I wrote a little idea if it helps you

for(var i = 0; i<12; i++){
var select = document.createElement("select");
select.setAttribute("name", "selectChildren");
select.setAttribute("id", "selectChildren");
var option = document.createElement("option");
option.setAttribute("value", "value");
option.innerHTML = i;

But I don't know how to add a entire drop down after my click event and for each children with his inputs.

I can give you more details if you need help =)

I need explanations if you have a solution, not only the solution, because I will not learn like this =D

Thank you for taking time on my issue =)


Use a different iterator for adding options to the select list

Since i is already used to add each set of inputs, use another variable (e.g. var j) when adding options to the select list.

Create the select list, then add options, then add the list to the DOM

var select = document.createElement("select");
select.setAttribute("name", "selectChildren");
select.setAttribute("id", "selectChildren" + i);
for (var j = 0; j < 12; j++) {
     var option = document.createElement("option");
     option.setAttribute("value", j+1);
     option.innerHTML = j + 1;
childrenContainer.appendChild(select); //Add the select list to the DOM