How to populate the options of a select element in javascript

风格不统一 提交于 2019-11-26 18:55:16

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

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

    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
        });

A dirty option would be to use divs and populate the select string (innerHTML) based on the previous selection. You can still use the langArray as mentioned above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!