An unobtrusive javascript function which binds dropdowns together in order to apply cascading behaviour. Child (cascaded) dropdown has a class pointing to the value of the father dropdown.
If javascript is not enabled, your application will run. The user will just get to see all the possible child dropdown options, which is better than seeing nothing (as in 100% javascript based cascading dropdowns).
//Applies cascading behavior for the specified dropdowns
function applyCascadingDropdown(sourceId, targetId) {
var source = document.getElementById(sourceId);
var target = document.getElementById(targetId);
if (source && target) {
source.onchange = function() {
displayOptionItemsByClass(target, source.value);
}
displayOptionItemsByClass(target, source.value);
}
}
//Displays a subset of a dropdown's options
function displayOptionItemsByClass(selectElement, className) {
if (!selectElement.backup) {
selectElement.backup = selectElement.cloneNode(true);
}
var options = selectElement.getElementsByTagName("option");
for(var i=0, length=options.length; i<length; i++) {
selectElement.removeChild(options[0]);
}
var options = selectElement.backup.getElementsByTagName("option");
for(var i=0, length=options.length; i<length; i++) {
if (options[i].className==className)
selectElement.appendChild(options[i].cloneNode(true));
}
}
//Binds dropdowns
function applyCascadingDropdowns() {
applyCascadingDropdown("categories", "items");
//We could even bind items to another dropdown
//applyCascadingDropdown("items", "foo");
}
//execute when the page is ready
window.onload=applyCascadingDropdowns;