根据数组jquery选择Option(2 dependent)

时间:2015-04-24 11:34:24

标签: jquery arrays

post_change_branch_tip

我上面有这个数组,我想把数组的[{ "subclass": "Class 1", "SubClass": [{ "subclass": "Class 1", "subid": "1", "price": "1.6625" }, { "subclass": "Class 1", "subid": "2", "price": "1.575" }] }, { "subclass": "Class 2", "SubClass": [{ "subclass": "Class 2", "subid": "1", "price": "3.0625" }, { "subclass": "Class 2", "subid": "2", "price": "2.8" }, { "subclass": "Class 2", "subid": "3", "price": "2.5375" }, { "subclass": "Class 2", "subid": "4", "price": "2.275" }] }] for (var i = 0; i < data.length; i++) { var SubClass = data[i].SubClass; for (var j = 0; j < SubClass.length; j++) { $(selectid).append('<option id=' + SubClass[j].subid + ' value="' + SubClass[j].subid + '">' + SubClass[j].subid + '</option>'); } $(selectclass).append('<option id=' + data[i].subid + ' value="' + data[i].subclass + '">' + data[i].subclass + '</option>'); } 值放到一个select中,然后在下一个select中放入subclass。我的问题是,我只想显示当前在我的代码中显示所有子代码的每个subid可用的subid

subclass

FIDDLE

以下是我对UPDATE所期望的内容,Class 1 1 and 2的{​​{1}}内容为Class 2

1 个答案:

答案 0 :(得分:1)

您需要使用更改事件处理程序

var selectclass = $('#selectclass');
selectclass.empty();
var selectid = $('#selectid');
selectid.empty();

$.each(data, function (i, item) {
    $('<option id=' + item.subid + ' value="' + item.subclass + '">' + item.subclass + '</option>').appendTo(selectclass).data('item', item);
});

selectclass.on('change.selectid', function () {
    var item = $(this).find('option:selected').data('item');
    selectid.empty();
    $.each(item.SubClass, function (i, sub) {
        $('<option id=' + sub.subid + ' value="' + sub.subid + '">' + sub.subid + '</option>').appendTo(selectid);
    });
}).trigger('change.selectid');

演示:Fiddle