Created
April 3, 2013 10:11
-
-
Save olimortimer/5299980 to your computer and use it in GitHub Desktop.
Create chained dropdowns on the fly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<select name="location_tree[1]" id="location-tree-1"> | |
<option value="0" selected="selected">Please Select...</option> | |
<option value="2">Africa</option> | |
<option value="203">Asia</option> | |
<option value="332">Asia Pacific</option> | |
<option value="1299">Caribbean</option> | |
<option value="1749">Central America</option> | |
<option value="1925">Europe</option> | |
<option value="17949">India & Indian Ocean</option> | |
<option value="18058">Middle East</option> | |
<option value="18102">South America</option> | |
<option value="19214">Southeast Asia</option> | |
<option value="19356">North America</option> | |
</select> | |
<script> | |
$(document).ready(function () { | |
$(document).on('change', 'select[name^="location_tree"]', function() { | |
var drop_id = $(this).attr('id').replace(/location-tree-/, ''); | |
var drop_id_new = parseInt(drop_id) + 1; | |
// Destroy our sibling dropdowns | |
var i = drop_id_new; | |
while($('#location-tree-'+i).length) { | |
$('#location-tree-'+i).remove(); | |
i++; | |
} | |
var id = $('#location-tree-'+drop_id).val(); | |
if(id == 0) return false; | |
$.getJSON('locations/ajaxDropdown', {location_id: id}, function(data) { | |
var items = []; | |
// For each item, create a dropdown option | |
$.each(data, function(key, val) { | |
items.push('<option value="' + key + '">' + val + '</option>'); | |
}); | |
// Only create our new dropdown if we have more than a 'Please Select...' option | |
if(items.length > 1) { | |
// Now create our new dropdown | |
$('#location-tree-'+drop_id).after('<select name="location_tree['+drop_id_new+']" id="location-tree-'+drop_id_new+'"></select>'); | |
// ...and add our items | |
$('#location-tree-'+drop_id_new).html(items); | |
} | |
}); | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment