2014-04-02 61 views
0

我可以從服務返回任何JSON。基於JSON,我需要動態創建SelectBoxes並在其中填入值。使用jQuery創建基於JSON的動態選擇框

EG-

JSON = { 
    "Level": [{ 
     "Product": [{ 
      "ID": "ID1", 
       "Brand": "Brand2", 
       "Type": "Type3", 
       "Line": "Line4", 
       "Family": "Family5" 
     }], 
      "Location": [{ 
      "City": "City1", 
       "State": "State2", 
       "Region": "Region3", 
       "Country": "Country4" 
     }], 
      "Time": [{ 
      "Day": "Day1", 
       "Week": "Week2", 
       "Month": "Month3", 
       "Quarter": "Quarter4", 
       "Year": "Year5" 
     }] 

    }] 
} 

在這種情況下,3個主要的選擇框將根據他們的子查詢框創建。 Like - OneMain SelectBox - 時間,在時間之下5個更多的選擇框, 第二個SelectBox - 位置,在該4個以上的選擇框之下等等。

我完全不知道如何使它動態到這樣的水平。

回答

3

試試這個,

var level=JSON['Level'][0]; 
for(var pr in level){ 
    var $select =$('<select/>'); 
    $select.append('<option>'+pr+'</option>'); 
    key=level[pr][0]; 
    for(k in key){ 
     $select.append('<option>'+key[k]+'</option>'); 
    } 
    $select.appendTo('body'); 
} 

Live Demo

0

您好我想這是你使用jQuery

var JSONS = { 
    "Level": [{ 
     "Product": [{ 
      "ID": "ID1", 
       "Brand": "Brand2", 
       "Type": "Type3", 
       "Line": "Line4", 
       "Family": "Family5" 
     }], 
      "Location": [{ 
      "City": "City1", 
       "State": "State2", 
       "Region": "Region3", 
       "Country": "Country4" 
     }], 
      "Time": [{ 
      "Day": "Day1", 
       "Week": "Week2", 
       "Month": "Month3", 
       "Quarter": "Quarter4", 
       "Year": "Year5" 
     }] 

    }] 
} 

$(document).ready(function(){ 
    $.each(JSONS.Level[0],function(key,val){ 
     var currentSection = val[0]; 

     var selectEle=$('<select id="'+key+'"></select>'); 
     $.each(currentSection,function(k,va){ 
      var op = "<option>"+va+"</option>"; 
      selectEle.append(op); 

     }); 

     $('#selectWrap').append(selectEle);   
    }); 



}); 
example,IAM什麼