Jason Kelly
Jason Kelly

Reputation: 2655

Dynamically adding option values to a selectbox from an array

I need your help.

I have the following function below, that reads data from an array and then dynamically adds option values to a selectbox.

Is there a way to modify the array such that I can specify the text and the option value to be added?

ABC,"testing"
DEF,"the system"
GHI,"further testing"
JKL,"desired results"

So the select box now resembles the following:

<select>
<option value="testing">ABC</option>
<option value="the system">DEF</option>
<option value="further testing">GHI</option>
<option value="desired results">JKL</option>
</select>

ie.

var y = [
"ABC",
"DEF",
"GHI",
"JKL"
]
for (var i = 0; i < y.length; i++ ){
    document.getElementById('select1').options[i]=new Option(y[i], y[i])
}

Upvotes: 1

Views: 102

Answers (3)

aash
aash

Reputation: 1323

Here is another way you can do it:

function populateOption(name, value){

    select = document.getElementById('selectbox');


    var opt = document.createElement('option');
    opt.value = value;
    opt.innerHTML = name;
    select.appendChild(opt);


}

text = {'ABC' : "testing",
        'DEF':"the system", 
        'GHI':"further testing",
        'JKL':"desired results"}
for(var key in text){
    populateOption(key, text[key]);
}

Here is the working code:

fiddle

Upvotes: 0

Vadim
Vadim

Reputation: 8789

Try this:

var arr = [],
    key,
    options = {
        'value1': 'text1',
        'value2': 'text2',
        'value3': 'text3'
    };

for(key in options) {
    if(options.hasOwnProperty(key)) {
        arr.push(['<option value="', key, '">', options[key], '</option>'].join(''));
    }
}
document.getElementById('select1').innerHTML = arr.join('');

Upvotes: 2

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

You would need to change the array of strings to an array of objects:

var y = [
    {toDisplay: "ABC", value: "testing"},
    {toDisplay: "DEF", value: "the system"},
    {toDisplay: "GHI", value: "further testing"},
    {toDisplay: "JKL", value: "desired results"}
];

for (var i = 0; i < y.length; i++) {
    document.getElementById('select1').options[i] = new Option(y[i].toDisplay, y[i].value);
}

Of course, you can call the parameters within the objects whatever you want (e.g. text instead of toDisplay), as long as you're consistent.

Upvotes: 2

Related Questions