Jan P
Jan P

Reputation: 29

Options for select in a loop

I want to create select elements and I´m using a for loop. For these elements I want to create options.

The options I want to create are in arrayList. My code is working partly. I can create all selects but only the options for the first 7 select elements, which is exactly the number of elements in the array. I dont think thats a coincendence but I dont know how I can fix this. All other selects just show undefined

I hope someone can help me out

Thank you and Kind Regards

const arrayinput = [a, b, c, d, e, f, g, h, i, j];

for (var i = 0; i < arrayinput.length; i++) {
  var myParent2 = SelectContainer;
  var arrayList = ["Green", "Red", "Yellow", "Blue", "Brown", " Grey", "Orange"];
  var SelectNew = document.createElement("select");
  SelectNew.setAttribute('class', 'SelectNew');
  SelectNew.setAttribute('id', 'SelectNew-' + i);
  myParent2.appendChild(SelectNew);

  for (var z = 0; z < arrayList.length; z++) {
    var option = document.createElement("option");
    option.value = arrayList[i];
    option.text = arrayList[i];
    SelectNew.appendChild(option);
  }
}
<div id="SelectContainer"></div>

Upvotes: 0

Views: 466

Answers (1)

Rishabh Jain
Rishabh Jain

Reputation: 184

You have to use arrayList[z] because in your code , you are using arrayList[i] So when i run for 7 , 8 ,9 iteration ,arrayList[i] doesn't exist , that's why it show undefined.

for (var i = 0; i < 10; i++) {
  var myParent2 = SelectContainer;
  var arrayList = ["Green", "Red", "Yellow", "Blue", "Brown", " Grey", "Orange"];
  var SelectNew = document.createElement("select");
  SelectNew.setAttribute('class', 'SelectNew');
  SelectNew.setAttribute('id', 'SelectNew-' + i);
  myParent2.appendChild(SelectNew);

  for (var z = 0; z < arrayList.length; z++) {
    var option = document.createElement("option");
    option.value = arrayList[z];
    option.text = arrayList[z];           
    SelectNew.appendChild(option);        
  }
}
<div id="SelectContainer"></div>

Upvotes: 1

Related Questions