使用jquery或Ajax从JSON文件中将数据填充到多个html下拉列表

时间:2012-02-09 12:00:23

标签: jquery html ajax json

我有三个下拉列表。默认情况下,这三个值均为“全部”。通过此值,第二个和第三个下拉列表将被禁用“ALL”值。当我们更改第一个下拉列表的值时,将启用第二个列表并填充与第一个列表中所选类别相关的子类别。当我们更改第二个列表的值(默认为“全部”)时,启用第三个列表并填充第二个列表类别的子类别。所有值都取自JSON文件:它的格式为

var accounts = ["WHDH","TF"];


var mediaGroups = {"WHDH": ["WHDH_1","WHDH_2"], "TF": ["TF_1","TF_2"]};


var clipUrls = {"WHDH_1": ["/live/whdh1/1","/live/whdh1/2","/live/whdh1/3"], "WHDH_2": ["/live/whdh2/1","/live/whdh2/2","/live/whdh2/3"], "TF_1": ["/live/tf1/1","/live/tf1/2","/live/tf1/3"], "TF_2": ["/live/tf2/1","/live/tf2/2","/live/tf2/3"]};

第一个列表是Account,第二个是Media Groups,Thrid是Clip URLS。

1 个答案:

答案 0 :(得分:1)

如果您尝试根据指定的对象构建选择列表 - 请尝试此

示例HTML:

<select id="first">
    <option value="all">All</option>
    <option value="WHDH">WHDH</option>
    <option value="TF">TF</option>
</select>

<select id="second">
    <option value="all">All</option>
</select>

<select id="third">
    <option value="all">All</option>
</select>

JavaScript:

var accounts = ["WHDH","TF"];
var mediaGroups = {"WHDH": ["WHDH_1","WHDH_2"], "TF": ["TF_1","TF_2"]};
var clipUrls = {"WHDH_1": ["/live/whdh1/1","/live/whdh1/2","/live/whdh1/3"], "WHDH_2": ["/live/whdh2/1","/live/whdh2/2","/live/whdh2/3"], "TF_1": ["/live/tf1/1","/live/tf1/2","/live/tf1/3"], "TF_2": ["/live/tf2/1","/live/tf2/2","/live/tf2/3"]};

$('#first').change(function() {
    // Remove all options and add the default All option
    $('#second').find('option')
    .remove()
    .end()
    .append('<option value="All">All</option>')
    .val('All');

    // loop mediaGroups and add options
    $.each(mediaGroups[$(this).val()], function(key, value) {   
     $('#second')
         .append($("<option></option>")
         .attr("value",value)
         .text(value)); 
    });
});

$('#second').change(function() {
    // Remove all options and add the default All option
    $('#third').find('option')
    .remove()
    .end()
    .append('<option value="All">All</option>')
    .val('All');

    // loop clipUrls and add the values based on other select list
    $.each(clipUrls[$(this).val()], function(key, value) {   
     $('#third')
         .append($("<option></option>")
         .attr("value",value)
         .text(value)); 
    });
});

这里的例子 - &gt; http://jsfiddle.net/Ac2na/