The code:
var newSelect=document.createElement('select');
index=0;
var optn = document.createElement("option");
//langArray is an array that contains different items..the size
//is not fixed for this array.
for(element in langArray)
{
//Now i want to assign each item in langArray to each option tag
//will it be sumthng like "optn.options[index]=new Option("Sports", "sportsvalue", true, false);
//optn.accept(langArray[0]);
index++;
}
I'm trying to get options populated by this way but its not coming all right as I don't know how to populate the options from an array in JS. Do I even have to use the loop or can I just assign the langArray to some property of select element and every thing will be up and running?
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.
来源:https://stackoverflow.com/questions/6601028/how-to-populate-the-options-of-a-select-element-in-javascript