How to populate the options of a select element in javascript

Solution 1:

You can create the option inside the loop;

for(element in langArray)
{
   var opt = document.createElement("option");
   opt.value= index;
   opt.innerHTML = element; // whatever property it has

   // then append it to the select element
   newSelect.appendChild(opt);
   index++;
}

// then append the select to an element in the dom

Solution 2:

You need to create your option element inside your loop, set attributes and text and append it to the select element:

var select = document.createElement('select'),
    option,
    i = 0,
    il = langArray.length;

for (; i < il; i += 1) {
    option = document.createElement('option');
    option.setAttribute('value', langArray[i].value);
    option.appendChild(document.createTextNode(langArray[i].text));
    select.appendChild(option);
}

This assumes that your langArray looks something like this:

var langArray = [
    {value: "val1", text: "text 1"},
    {value: "val2", text: "text 2"}
];

You'll need to tweak the code to match your array

Solution 3:

    var dynamicSelect = document.getElementById("selectID");

        langArray.forEach(function(item){ 
        {
                var newOption = document.createElement("option");
                newOption.text = item.toString();//item.whateverProperty

                dynamicSelect.add(newOption);

                //new select items should populated immediately
        });