Cascading Dropdown
Cascading dropdown in jQuery. Debugging extra firing of change events.
by TheFiddler
HTML
<script src="http://www.quicksource.com/projects/jsfiddle/js/jquery.selectboxes.min.js"></script>
<div class="chooseSteps">
<select class="cascade">
<option value="-">-- Step1 --</option>
<option value="1">v11</option>
<option value="2">v12</option>
<option value="5">v15</option>
<option value="6">v16</option>
</select>
<select class="cascade">
<option value="-">-- Step2 --</option>
</select>
</div>
JavaScript
//trigger change event on selects
$('select .cascade').change(updateDropDowns);
//initialize
var currentSelect = 1;
var nextSelect =2;
var currentDDL= '.chooseSteps select:nth-child('+ currentSelect +')';
var nextDDL = '.chooseSteps select:nth-child('+ nextSelect +')';
//disable next
$(nextDDL).attr('disabled', true);
function updateDropDowns() {
var chooseSteps = $(this).closest('.chooseSteps')
var currentDDL= '.chooseSteps select:nth-child('+ currentSelect +')';
var nextDDL = '.chooseSteps select:nth-child('+ nextSelect +')';
//loop to disable others
//ddStep3.attr('disabled', true).find('option:gt(0)').remove();
//ddStep4.attr('disabled', true).find('option:gt(0)').remove();
// Check in case reselected the default.
// Reset and disable this step.
if ($(currentDDL).val() == "-") {
alert("FIRST");
nextDDL.attr('disabled', true).find('option:gt(0)').remove();
return;
}
// Enable next step
$(nextDDL).attr('disabled', false).find('option:gt(0)').remove();
// Simulate ajax call to get step2 values based on step1.
var numItems = 3;
$(nextDDL).addOption("1", "v21", false);
$(nextDDL).addOption("2", "v22", false);
$(nextDDL).addOption("7", "v27", false);
// If only one option other than the default, select it,
// and fire the change event for the next dropdown.
// Chrome now requires all options to have a value for this to work; empty string didn't work.
if (numItems == 1) { // The count after the default.
$(nextDDL).attr('selectedIndex', 1).change(); // 0-n. Fire the event.
}
}