1

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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('');

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.