Reputation: 1459
I am trying to create a Make, Model, and Year select drop down similar to many car sites such as Autotrader. However I am having difficulty getting the second select drop down to populate after the user first selects the initial drop down. Hoping for suggestions.
My HTML:
<div class="col-md-4">
<select id="make" class="form-control">
<option>Make</option>
<option>Chevrolet</option>
<option>Ford</option>
<option>GMC</option>
<option>Toyota</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-4 col-md-offset-4 mob">
<select id="models" class="form-control models" disabled>
<option>Model</option>
<option>Silverado</option>
<option>Suburban</option>
<option>Tahoe</option>
</select>
</div>
</div>
My javascript:
//setup arrays
Chevrolet = ['Silverado','Suburban','Tahoe'];
Ford = ['F150','Taurus','Pinto','Bronco'];
Toyota = ['Camry','Tacoma','4Runner'];
GMC = ['blah1','blah2','blah3'];
$('#make').change(function() {
$('#models').prop('disabled', true);
$("#models").html(""); //clear existing options
var newOptions = window[this.value]; //finds the array w/the name of the selected value
//populate the new options
for (var i=0; i<newOptions.length; i++) {
$("#models").append("<option>"+newOptions[i]+"</option>");
}
$('#models').prop('disabled', false); //enable the dropdown
});
Here is my jsfiddle: http://jsfiddle.net/rynslmns/W9TLT/
Upvotes: 0
Views: 1283
Reputation: 78630
You didn't include jquery in your fiddle.
That said, you shouldn't really use a global, instead make your own object and modify your code slightly:
$(function(){
//setup arrays
var cars = {
"Chevrolet" : ['Silverado','Suburban','Tahoe'],
"Ford" : ['F150','Taurus','Pinto','Bronco'],
"Toyota" : ['Camry','Tacoma','4Runner'],
"GMC" : ['blah1','blah2','blah3']
};
$('#make').change(function() {
$("#models").html(""); //clear existing options
var newOptions = cars[this.value]; //finds the array w/the name of the selected value
//populate the new options
for (var i=0; i<newOptions.length; i++) {
$("#models").append("<option>"+newOptions[i]+"</option>");
}
$('#models').prop('disabled', false); //enable the dropdown
});
});
Another note. Disabling the dropdown at the start of your code and then enabling it at the end has no effect other than to enable the dropdown. Due to the single-threaded nature of browsers/javascript, the disable never really happens. All that matters is what it is set to when the code completes.
Upvotes: 2
Reputation: 4463
Your fiddle doesn't have jQuery loaded!
$('#make').change(function() {
$('#models').prop('disabled', true);
$("#models").html(""); //clear existing options
var newOptions = window[this.value]; //finds the array w/the name of the selected value
//populate the new options
for (var i=0; i<newOptions.length; i++) {
$("#models").append("<option>"+newOptions[i]+"</option>");
}
$('#models').prop('disabled', false); //enable the dropdown
});
Upvotes: 1