sloga
sloga

Reputation: 642

what is best way to get select options, values from js array

I'm trying to write js so that my select option dropdown gets the value and text from my array. js is new for me. jsfiddle

I need the value to be the number and text the text in quotes from:

var locations = [
    [23, 'Main Room'],
    [1, 'Main Lobby'],
    [2, 'Training Room'],
    [56, 'Main Office'],
    [57, 'Lower Office'],
    [9, 'Lower Lobby'],
    [62, 'Conference Room'],
    [22, 'Outdoor Patio'],
    [63, 'Upper Lobby']
    ];

var select = document.getElementById("selectRoom");
for(var i = 0; i < locations.length; i++) {
    var opt = locations[i];
    var el = document.createElement("option");
    el.textContent = opt; // I just want the text within quotes from 
    el.value = opt; // I just want the number from opt
    select.appendChild(el);
}

or should my array look like? locations = { "23": "Main Room", "1": "Main Lobby" };

Upvotes: 1

Views: 205

Answers (3)

Musa
Musa

Reputation: 97717

To get the value from the array you'll have to use locations[i][0] and locations[i][1] for the text

Also you can use the Option constructor to minimize your code

for(var i = 0; i < locations.length; i++) {
    var el = new Option(locations[i][1], locations[i][0]);
    select.appendChild(el);
    //select.add(el, null); I think there is an issue with add in IE
}

Upvotes: 0

omma2289
omma2289

Reputation: 54649

Your locations are arrays with two elements, your value is in index 0 and your text in index 1

for(var i = 0; i < locations.length; i++) {
    var opt = locations[i];
    var el = document.createElement("option");
    el.textContent = opt[1]; 
    el.value = opt[0];
    select.appendChild(el);
}

I you want to use an object instead, which is preferable, then setup your locations as @Hallvar suggests, I was going to edit with his same answer but he beat me to it

Upvotes: 3

Hallvar Helleseth
Hallvar Helleseth

Reputation: 1867

Quick fix, change to:

el.textContent = opt[1]; // I just want the text within quotes from 
el.value = opt[0]; // I just want the number from opt

However, like you are thinking, it is more common to use an object for this:

var locations = {
    23: 'Main Room',
    1: 'Main Lobby',
    2: 'Training Room',
    56: 'Main Office',
    57: 'Lower Office',
    9: 'Lower Lobby',
    62: 'Conference Room',
    22: 'Outdoor Patio',
    63: 'Upper Lobby'
    };

var select = document.getElementById("selectRoom");
for(var key in locations) {
    if(location.hasOwnProperty(key)) {
        var el = document.createElement("option");
        el.textContent = locations[key]; // I just want the text within quotes from 
        el.value = key; // I just want the number from opt
        select.appendChild(el);
    }
}

Upvotes: 2

Related Questions