Reputation: 55
I need to be able select multiple vehicles on a web page using JQuery. Selecting the Make in the first dropdown populates the second dropdown with the Models for that Make.
ddlMake1 should populate ddlModel1
ddlMake2 should populate ddlModel2
ddlMake3 should populate ddlModel3
Initially populating the dropdowns works fine, and if I only add one set, it works just fine. When I add a second or third set, it populates all sets properly, but if I select any of the makes, it populates the Models in the last set.
selecting ddlMake1/2/3 populates ddlModel3
I would like he model to be 'connected' to it's make. Where am I going wrong?
<body>
<select id="ddlMake1"></select><select id="ddlModel1"></select><br />
<select id="ddlMake2"></select><select id="ddlModel2"></select><br />
<select id="ddlMake3"></select><select id="ddlModel3"></select>
</body>
<script>
$(document).ready(function () {
loadDropdownData('ddlMake1', 'ddlModel1');
loadDropdownData('ddlMake2', 'ddlModel2');
loadDropdownData('ddlMake3', 'ddlModel3');
});
</script>
function loadDropdownData(make, model) {
var data = {
'Acura': { 'CSX': [], 'EL': [], 'ILX': []},
'Audi': { 'A4': [], 'A5': [], 'A6': []},
'BMW': { '1 Series': [], '2 Series': [], '3 Series':[]}
};
$a = $("#" + make);
$b = $("#" + model);
$a.html('');
for (var prop in data) {
var first = prop;
$a.append($("<option>").attr("value", first).text(first));
}
$a.change(function () {
var firstkey = $(this).val();
$b.html('');
for (var prop in data[firstkey]) {
var second = prop;
$b.append($("<option>").attr("value", second).text(second));
}
}).change();
}
Upvotes: 0
Views: 1121
Reputation: 2175
your $b variable was being declared outside of the scope of your function. By adding var you create the variable new every time the function is called.
$(document).ready(function () {
loadDropdownData('ddlMake1', 'ddlModel1');
loadDropdownData('ddlMake2', 'ddlModel2');
loadDropdownData('ddlMake3', 'ddlModel3');
});
function loadDropdownData(make, model) {
var data = {
'Acura': { 'CSX': [], 'EL': [], 'ILX': []},
'Audi': { 'A4': [], 'A5': [], 'A6': []},
'BMW': { '1 Series': [], '2 Series': [], '3 Series':[]}
};
var $a = $("#" + make);
var $b = $("#" + model);
$a.html('');
for (var prop in data) {
var first = prop;
$a.append($("<option>").attr("value", first).text(first));
}
$a.change(function () {
var firstkey = $(this).val();
$b.html('');
for (var prop in data[firstkey]) {
var second = prop;
$b.append($("<option>").attr("value", second).text(second));
}
}).change();
}
Upvotes: 1
Reputation: 9634
Problem is scope of variables, use this:
var $a = $("#" + make);
var $b = $("#" + model);
Upvotes: 1