0

我有一个要求,我可以使用JS Fiddle 下拉列表来填充州和城市。我在这样的excel表中有数据

State           City
Andhra Pradesh  Kadapa
Andhra Pradesh  Kadiri
Andhra Pradesh  Kagaznagar
Andhra Pradesh  Kakinada
Andhra Pradesh  Kalyandurg
Andhra Pradesh  Kamareddy
Assam           Karimganj
Assam           Kokrajhar
Bihar           Katihar
Bihar           Kanti
Bihar           Kishanganj
Bihar           Khagaria
Bihar           Kharagpur
Chhattisgarh    Kawardha
Chhattisgarh    Kanker
Chhattisgarh    Korba
Chhattisgarh    Kondagaon
Gujarat         Kapadvanj
Gujarat         Karjan
Gujarat         Kalavad
Gujarat         Kadi
Gujarat         Kalol
Haryana         Karnal
Haryana         Kalan Wali
Haryana         Kaithal

用于填充下拉列表的js小提琴如下

--from here I want to input data from excel sheet or CSV or any other better suggestions in place of following code.
var data = [ // The data
    ['ten', [
        'select','eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];
--up to here.-----------------------------------

现在我想将数据传递给下面的函数

$a = $('#State'); // The dropdowns
$b = $('#City');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][3]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

这是下拉菜单

<select id=state></select></br>
<select id=city></select>

我关心的是如何

4

1 回答 1

1

将文件转换为JSON 数据以便于访问——数据不应该经常更改,所以这应该不是问题。然后您可以通过AJAX加载它:

$.getJSON('ajax/cities.json', function(data) {
    var $opt = $("<option>")
       .attr("value",data.city)
       .text(data.state);
    $('#state').append($opt);
});

...或类似的东西。

于 2012-06-18T13:11:56.757 回答