使用对象数组填充并使用jQuery

时间:2015-11-10 19:54:30

标签: javascript jquery html arrays drop-down-menu

我需要使用对象数组填充三个下拉列表:

HTML:

<select id="crop"></select>
<select id="type"></select>
<select id="practice"></select>

数据(它更大):

var crops = [{
"Crop": "Annual Forage ",
    "Type": " No Type Specified ",
    "Practice": " Dec - Jan Index Interval",
    "CropCode": 0332
}, {
"Crop": "Annual Forage ",
    "Type": " No Type Specified ",
    "Practice": " Feb - Mar Index Interval",
    "CropCode": 0332
 }, {
"Crop": "Annual Forage ",
    "Type": " No Type Specified ",
    "Practice": " Jan - Feb Index Interval",
    "CropCode": 0332
 }, {
"Crop": "Apiculture ",
    "Type": " No Type Specified ",
    "Practice": " Jun - Jul Index Interval",
    "CropCode": 1191
 }, {
"Crop": "Apiculture ",
    "Type": " No Type Specified ",
    "Practice": " Jan - Feb Index Interval",
    "CropCode": 1191
 }, {
"Crop": "Apiculture ",
    "Type": " No Type Specified ",
    "Practice": " Mar - Apr Index Interval",
    "CropCode": 1191
  }, {
"Crop": "Apiculture ",
    "Type": " No Type Specified ",
    "Practice": " Sep - Oct Index Interval",
    "CropCode": 1191
 }, {
"Crop": "Apples",
    "Type": " Processing",
    "Practice": " Irrigated",
    "CropCode": 0054
 }, {
"Crop": "Apples",
    "Type": " Processing ",
    "Practice": " Non-Irrigated",
    "CropCode": 0054
 }, {
"Crop": "Apples ",
    "Type": " Processing ",
    "Practice": " Non-Irrigated(Oc)",
    "CropCode": 0054
 }, {
"Crop": "Barley ",
    "Type": " Spring Malting ",
    "Practice": " Irrigated",
    "CropCode": 0091
 }];

首先,我删除了重复的Crop,然后填充第一个下拉列表:

var options = unique(crops, "Crop");
var selectOptions = '';

for (i = 0; i < options.length; i++) {

selectOptions += '<option value="' + options[i] + '">' + options[i] + '</option>';
}
$('#crop').append(selectOptions).on('change', function () {
});

//Eliminates duplicates
function unique(list, attr) {
var result = [];
$.each(list, function (i, e) {
    if ($.inArray(e[attr], result) == -1) result.push(e[attr]);
});
return result;
}

到目前为止,这个工作正常,但是我需要填写第二个下拉列表与通讯员Type和第三个下拉列表及其各自的Practice。我被困在这里,我无法做到这一点。我需要的是,当选择在firt下拉中时,让我们说:“Apiculture”,只有“Apiculture”的TypePractice填充第二和第三个下拉列表。提前谢谢。

Fiddle

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您可以迭代each crop对象并检查crop是否与下拉列表的值匹配,如果匹配,则填充其他两个相应的下拉菜单:

$('#crop').append(selectOptions).on('change', function () {
    var selected = $(this).find('option:selected').val();
    $('#type, #practice').empty();
    $.each(crops, function(i, v) {
        if (v.Crop == selected) {
            $('#type').append('<option value="'+v.Type+'">'+v.Type+'</option>');
            $('#practice').append('<option value="'+v.Practice+'">'+v.Practice+'</option>');
        }
    });
});

Example Fiddle