且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

3 dropdown 根据另一个[Cascading dropdown]中的选择填充

更新时间:2023-10-12 21:19:34

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

Try something like this.. I had to slightly change the structure of the data object. Next to get the value of the dropdown you can just do .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();

检查小提琴