jquery使用json数据填充下拉列表

时间:2012-02-27 18:00:41

标签: jquery json drop-down-menu

美好的一天,

我已经在网上看过并使用json和jquery阅读有关下拉列表的帖子。但是我似乎无法使我的语法正确。当页面加载时,我希望城镇下拉列表包含所有城镇。一旦用户选择社区,则只显示该城镇的社区。

感谢任何帮助。请在此处查看我的代码http://jsfiddle.net/latoyale/XgxCP/1/

1 个答案:

答案 0 :(得分:0)

我做了一个工作分叉:http://jsfiddle.net/ccync/

对于后人,JavaScript代码如下:

// JSON data start

var data = [
     [
                {optionValue: 0,url: 'Choose Town',community: 'Choose Town'},
                {optionValue: 1,url: '/dutchess/amenia',community: 'Amenia'},
                {optionValue: 2,url: '/dutchess/arlington',community: 'Arlington'},
                {optionValue: 3,url: '/dutchess/barrytown',community: 'Barrytown'}
     ],


            [   {optionValue: 0,url: 'Choose Town',community: 'Choose Town'},
                {optionValue: 32,url: '/orange/Campbell-hall',community: 'Campbell Hall'},
                {optionValue: 33,url: '/orange/central-valley',community: 'Central Valley'},
                {optionValue: 34,url: '/orange/chester',community: 'Chester'},
   ]

           ];

// JSON data end


$(function() {

    $('#page-changer')[0].reset(); // resets form onload

    var $county = $('#county');
    var $township = $('#township');  
    function updateTownshipOptions(){
        var selected = $county.val();
        if (selected) {
            options = [];
            var selected_data = data[$county.val()-1];
            for (var i=0; i<selected_data.length; i++) {
                options.push('<option value="'+selected_data[i].optionValue+'">'+selected_data[i].community+'</option>');
            }
            $township.html(options.join(''));
        }
    }    
    updateTownshipOptions();
    $county.change(updateTownshipOptions);

});