I have three dropdowns that I need to populate using an object array:
HTML:
<select id="crop"></select>
<select id="type"></select>
<select id="practice"></select>
Data (it is much larger):
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
}];
First I eliminate the Crop that is a duplicate, and then populate the first dropdown:
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;
}
So far this works just fine, but then I need to populate the second drop down with the correspondent Type and the third with its respective Practice. I'm stuck here, and I can't get it to do it. I need that when a selection is made in the firt drop down, let's say: "Apiculture", only the Type and Practice for "Apiculture" populate the second and third dropdowns. Thanks in advance.