I have been given an array in the following format and need to put it into two drop down boxes one with make and the other with model based on the first selection. (the actual array is huge, but I have just included the first few)
var aMember = [{
"Make": "other",
"Models": ["other"]
}, {
"Make": "Boat",
"Models": ["Over 21 ft.", "Under 21 ft."]
}, {
"Make": "Motorcycle",
"Models": ["Over 600cc", "Under 600cc"]
}];
I need to have a make combo box with Other, Boat and Motorcycle, which when selected populates the second combo box with the options.
I have done almost no JavaScript before, but have tried the following, which does not work.
I really don’t know if I am anywhere near to what I need.
<html>
<head>
<script>
var cars =[{"Make":"other","Models":["other"]},{"Make":"Boat","Models":["Over 21 ft.","Under 21 ft."]},{"Make":"Motorcycle","Models":["Over 600cc","Under 600cc"]}];
function populateDropdown(drop, items) {
drop.empty();
for(var i = 0; i < items.length; i++) {
drop.append('<option value=' + i + '>' + items[i].Make + '</option>');
}
drop.show();
}
populateDropdown( $('#Makes'), cars );
$('#Models').change(function() {
var modelIndex = $(this).val();
var model = Models[modelIndex ];
populateDropdown( $('#Models'), cars.Models);
});
</script>
</head>
<body onload = "populateDropdown( $('#Makes'), cars );">
<form>
MAKE:
<select name = 'Makes'>
</select>
MODEL:
<select name = 'Models'>
</select>
</select>
</form>
</body>
</html>
Thanks
$.grepto filter out the current make, and then fetch the models of that make.$.mapto map the array with all data to an array of makes.$.eachcan be used.$("<option>").val(...).text(...)to build theoptiona little cleaner.$(function() {...})to wait until the DOM is ready.drop.show()is not needed since bothselects are already visibleModelsonModels‘s change event. I think you mean to run that onMakes‘s change event.nameinstead ofid. Also you should not use spaces around the=in HTML attributes.This is a corrected version: http://jsfiddle.net/zJTnw/1/.