Cascading dropdown
by karthick Chandran
HTML
<label for="Preference 1">Preference 1</label>
<select id="borough" name="borough">
<option value="">SELECT</option>
</select>
<label for="Preference 2">Preference 2</label>
<select id="school" name="school">
</select>
JavaScript
var boroughs = {
305 : {
name:"bro",
schools: [
{val:2012,name:"test school 1"},
{val:6079,name:"test school 2"},
{val:2013,name:"test school 3"}
]
},
303: {
name:"bex",
schools: [
{val:6000,name:"test school 4"},
{val:5200,name:"test school 5"},
{val:5201,name:"test school 6"}
]
}
}
$(function() {
$.each(boroughs,function(num,borough) {
$('#borough').append('<option value="'+num+'">'+borough.name+'</option>');
});
$('#borough').on("change",function() {
var br = this.value, $schoolDrop=$("#school")
window.console && console.log(br);
$("option:gt(0)",$schoolDrop).remove();
if (br) {
$("option:eq(0)",$schoolDrop).text("Please select school for "+boroughs[br].name);
var schools = boroughs[br].schools;
$.each(schools,function(_,school) {
$schoolDrop.append('<option value="'+school.val+'">'+school.name+'</option>');
});
}
else {
$("option:eq(0)",$schoolDrop).text("<-- Select borough first to narrow down");
}
});
});