2013-07-30 113 views
1

我想寫js,以便我的選擇下拉列表中獲取值和我的數組中的文本。 js對我來說是新的。 jsfiddle什麼是最好的方式來獲得選擇選項,從js數組值

我需要的值是數字和文本的文本引號:

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

或應我的數組是什麼樣子? locations = {「23」:「主廳」,「1」:「主大廳」};

+0

快捷鍵:新選項(「key」,「value」); – dandavis

回答

2

快速修復,更改爲:

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

但是,像你所想,這是比較常見的使用對象本:

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

我最終使用了快速修復而不是對象,但我認爲它會派上用場。另一個說明,你知道我可以如何將數組/對象放入extjs可滾動菜單嗎? – sloga

3

你的位置是具有兩個元素數組,你的價值是在索引0和索引文本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); 
} 

我要使用的對象,而不是,這是優選的,然後設置你的位置爲@ Hallvar建議,我會與他同樣的答案編輯,但他打我給它

0

要獲得該數組中的價值,你將不得不使用locations[i][0]locations[i][1]文本

您也可以使用選項的構造,以儘量減少你的代碼

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 
} 
相關問題