Dependent Dropdowns Scratchpad
HTML
<div id="edit-loc-wrapper" class="views-exposed-widget views-widget-filter-field_project_location_tid">
<label for="edit-loc">City</label>
<div class="views-widget">
<div class="form-item form-type-select form-item-loc">
<select id="edit-loc" name="loc" class="form-select">
<option value="All" selected="selected">- ANY CITY/AREA -</option>
<option value="1">BOGOTÁ</option>
<option value="2">-SAN RAFAEL</option>
<option value="5">ZIPAQUIRÁ</option>
<option value="6">-MADELENA</option>
<option value="7">-SANTA ANA</option>
<option value="3">CALI</option>
<option value="4">-CHIPICHAPE</option>
</select>
</div>
</div>
</div>
JavaScript
/*
* Notes:
* - The fiddle does not use Drupal.t(), so you must do it when implementing it on your site.
*/
(function($) {
$(document).ready(function() {
var parents = {};
var srcSelect = 'edit-loc'; // id of the select containing the original, flat list of options
// Any option having this character(s) at least once will be considered child
// It is assumed this "magic" word is found before the part of the option that
// must be preserved when put into the level2 select
var childChar = '-';
var childCharLength = 1; // Length of childChar
var level1Label = '- ANY CITY -'; // "all" values text for level 1 select
var level2Label = '- ANY AREA -'; // "all" values text for level 2 select
var level1Id = 'city'; // Id to use for the level1 select
var level2Id = 'area'; // Id to use for the level2 select
var allOptionValue = 'All'; // value of the "all" option in the srcSelect
// Returns true if the text of the option has the childChar
function isChildItem(opt) {
var optText = $(opt).attr('text');
return optText.indexOf(childChar) == -1 ? false: true;
}
// Stores the latest parent found
var curParentVal = null;
// Clones an option to the appropriate select in the hierarchy
function addOption(parent, child, opt) {
var optVal = $(opt).attr('value');
var optText = $(opt).attr('text');
var childCharPos = optText.indexOf(childChar);
var cloneOpt = $(opt).clone();
if (! isChildItem(opt)) {
$('#' + parent).append(cloneOpt);
curParentVal = optVal;
} else {
var childOptText = optText.slice(childCharPos+childCharLength);
// Prepares the clone before appending it
$(cloneOpt)
...