2015-03-03 138 views
0

我試圖設置使用JSON數據的級聯下拉列表。我有點工作,但需要一些幫助,讓第二層按預期工作。目前它似乎在抓取數組中的數字。Json級聯下拉列表

理想的情況下我的二線我要顯示在下拉列表中的選項文本的文本,我想使用id字段的JSON作爲選項的值。

var data = { 
      "Crime":[ 
       {"id":"1","text":"Number of police"}, 
       { "id":"2","text":"Number of crimes"} 
        ], 
      "Health":[ 
       {"id":"3","text":"Number of doctors"}, 
       {"id":"4","text":"Number of hospital visits"}, 
       {"id":"5","text":"Number of nurses"} 
        ], 
       } 

我有一個jsfiddle顯示我到目前爲止。

很高興使用任何組合的JavaScript/jQuery效果最好。

+0

工作撥弄http://jsfiddle.net/tc1f3kup/3/請接受的答案,如果它爲你工作 – 2015-03-03 08:49:42

回答

1

您使用for..in的方式似乎不正確。如果指出的集合(data[this.value],在這種情況下)不是簡單數組,則question變量將不包含整個值。相反,它將包含第一行,第二行等的索引。我請你閱讀這一個更深入的瞭解:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

這裏這條線

questionSel.options[questionSel.options.length] = new Option(question, question); 

必讀這樣

questionSel.options[questionSel.options.length] = new Option(
             data[this.value][question].text, 
             data[this.value][question].id); 

這裏是在此之後更新的小提琴已更改:

http://jsfiddle.net/tc1f3kup/2/

+0

感謝@bundleofjoy爲一個有效的答案和一個好的描述。現在我會進一步閱讀! – rowanwins 2015-03-03 10:50:33

0

請儘量將

var data = { 
     "Crime":[ 
      {"id":"1","text":"Number of police"}, 
      { "id":"2","text":"Number of crimes"} 
       ], 

     "Health":[ 
      {"id":"3","text":"Number of doctors"}, 
      {"id":"4","text":"Number of hospital visits"}, 
      {"id":"5","text":"Number of nurses"} 

       ], 

      } 
window.onload = function() { 
     var themeSel = document.getElementById("theme"), 
     questionSel = document.getElementById("questions"); 
     for (var theme in data) { 
      themeSel.options[themeSel.options.length] = new Option(theme, theme); 
     } 
     themeSel.onchange = function() { 
      questionSel.length = 1; // remove all options bar first 
      if (this.selectedIndex < 1) return; // done     
       for(var i=0;i<data[this.value].length;i++) 
       {       
        questionSel.options[questionSel.options.length] = new Option(data[this.value][i].text, data[this.value][i].id); 
       } 



     } 
} 

工作撥弄 http://jsfiddle.net/tc1f3kup/3/

+0

認爲@ Nitu-Bansal,你的答案奏效,儘管接受的答案提供的解釋幫助我提供了更多關於我哪裏出錯的信息。雖然謝謝! – rowanwins 2015-03-03 10:51:48