Skip to content

Instantly share code, notes, and snippets.

@avidenov
Created December 5, 2015 07:05
Show Gist options
  • Save avidenov/c2cb3a33593abcd286ab to your computer and use it in GitHub Desktop.
Save avidenov/c2cb3a33593abcd286ab to your computer and use it in GitHub Desktop.
Dependent selection JS that works with form model binding
var $ = jQuery;
$(document).ready(function(){
listenForSpecialtySelect();
});
function listenForSpecialtySelect(){
// Set initialy on load
setSpecialtySelect();
// Listen on change
$('input[name="academic_level"]').on('change', function(){
setSpecialtySelect();
});
}
function setSpecialtySelect(){
academicLevel = $('input[name="academic_level"]:checked').val();
academicLevelOptions = $('select[name="specialty_id"] optgroup[label="'+academicLevel +'"] option');
originalSelect = $('select[name="specialty_id"]');
filteredSelect = $('select[name="specialty_select"]');
// Clear the filtered select
filteredSelect.html('');
// Clone the option of the selected academicLevel
academicLevelOptions.each(function(key, option){
$(option).clone().appendTo(filteredSelect);
});
// Update the original select with the filteredSelect val
// after the academicLevel is selected
originalSelect.val(filteredSelect.val());
// Update the originalSelect on filteredSelect change
filteredSelect.on('change', function(){
originalSelect.val(filteredSelect.val());
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment