【问题标题】:3 dropdown Populate based on selection in another [Cascading dropdown]3 dropdown 根据另一个 [Cascading dropdown] 中的选择填充
【发布时间】:2013-05-18 10:54:03
【问题描述】:

我是 Java 脚本的新手。在这里,我有 2 个下拉 Fiddle 的工作示例。

HTML:

<select id=a></select>
<select id=b></select>
<select id=c></select>

JavaScript:

var data = [ // The data
    ['ten', [
        'eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];

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

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][2]; // 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

让我知道如何在此代码中再添加一个下拉菜单。

谢谢

【问题讨论】:

  • Raka 你能再解释一下你的问题吗
  • 嗨,目前我正在使用上面的代码来表示“国家”和“州”下拉。州下拉菜单将更新基于国家/地区的选择。现在我需要添加城市字段以根据州选择进行更新。

标签: jquery drop-down-menu populate


【解决方案1】:

试试这样的.. 我不得不稍微改变data 对象的结构。接下来要获取下拉列表的值,您只需执行.val()

var data = {
    'ten': {
        'eleven': [11, 1111, 111111],
        'twelve': [12, 1212, 121212]
    },
    'twenty': {
        'twentyone': [21, 2121, 212121],
        'twentytwo': [22, 2222, 222222]
    }
},
$a = $('#a'); // The dropdowns
$b = $('#b');
$c = $('#c');

for (var prop in data) {
    var first = prop;
    $a.append($("<option>"). // Add options
    attr("value", first).
    text(first));
}

$a.change(function () {
    var firstkey = $(this).val();
    $b.html(''); // Clear existing options in second dropdown
    for (var prop in data[firstkey]) {
        var second = prop;
        $b.append($("<option>"). // Add options
        attr("value", second).
        text(second));
    }
    $b.change();
}).change(); // Trigger once to add options at load of first choice

$b.change(function () {
    var firstKey = $a.val(),
        secondKey = $(this).val();
    $c.html(''); // Clear existing options in second dropdown
    for(var i = 0; i < data[firstKey][secondKey].length; i++) {
        var third = data[firstKey][secondKey][i]
        $c.append($("<option>"). // Add options
        attr("value", third).
        text(third));
    }
    $c.change();
}).change();

Check Fiddle

【讨论】:

  • 完全符合我的预期。谢谢
  • @Raka.. 很高兴能帮上忙 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多