Created
December 5, 2015 07:05
-
-
Save avidenov/c2cb3a33593abcd286ab to your computer and use it in GitHub Desktop.
Dependent selection JS that works with form model binding
This file contains 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
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