1

I tried to make <option>s with the content in a select tag using a for loop

var content = {
  0: "water"
  1: "tea"
  2: "coffee"
  3: "soda"
};
var selectTest = document.getElementById("test");
var createOpption = document.createElement("option");
var addOptionContent;

for (var i = 0; i < content.lenght; i++) {
  addOptionContent = document.createTextNode(content[i]);
  createOpption.appendChild(addOptionContent);
  selectTest.appendChild(createOpption);
}
<select id="test"></select>

I expect that each content will be in its own option tag but the result is that all content was in one option tag

j08691
  • 204,283
  • 31
  • 260
  • 272
Amir Makram
  • 12,030
  • 3
  • 13
  • 25
  • Typo in `content.lenght`. Also, your content variable is invalid. And for the length of an object, see https://stackoverflow.com/questions/5223/length-of-a-javascript-object – j08691 Apr 03 '19 at 17:36
  • An object is not an array and has no length at all. Also you don't append to option , you want an option for each item – charlietfl Apr 03 '19 at 17:37

2 Answers2

0

just create a Node for each not before

    let content = {
      0: "water",
      1: "tea",
      2: "coffee",
      3: "soda"
    };
    let selectTest = document.getElementById("test");


   for (let i in content) {
   let createOpption = document.createElement("option");
   createOpption.textContent=content[i];
   selectTest.appendChild(createOpption);
}

I also found this

selectTest.add(createOpption) 

does the same thing might be better

jonathan Heindl
  • 844
  • 7
  • 16
0

Use a for in loop to iterate object. You are treating content as an array which it isn't.

You also want a new element for each iteration

You can also use new Option(text, value, defaultSelected, selected) to create an <option>

var content = {
  0: "water",
  1: "tea",
  2: "coffee",
  3: "soda"
};
var selectTest = document.getElementById("test");


for (var key in content){
  var createOpption = new Option( content[key], key);
  selectTest.appendChild(createOpption)
}
<select id="test"></select>
charlietfl
  • 170,828
  • 13
  • 121
  • 150