Created
August 11, 2011 16:18
-
-
Save edzhelyov/1140062 to your computer and use it in GitHub Desktop.
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
$(function() { | |
$('select[data-nested-select]').each(function() { | |
var select = $(this), | |
groupName = select.data('nested-select'), | |
optgroups = select.find('optgroup'), | |
options = select.find('optgroup option'), | |
groupSelect = $('<select>'), | |
promptOption = makeOption(groupName, null, false); | |
groupSelect.append(promptOption); | |
optgroups.detach(); | |
optgroups.each(function(index) { | |
var optgroup = $(this), | |
name = this.label, | |
children = optgroup.children(), | |
selected = children.is(':selected'), | |
groupOption = makeOption(name, index, selected); | |
groupOption.data('options', children); | |
groupSelect.append(groupOption); | |
}); | |
groupSelect.change(function() { | |
var optionsInGroup = groupSelect.find('option:selected').data('options') || [], | |
hiddenOptions = options.not(optionsInGroup); | |
hiddenOptions. | |
attr('selected', false). | |
detach(); | |
select.append(optionsInGroup); | |
}); | |
groupSelect.insertBefore(select); | |
groupSelect.change(); | |
function makeOption(text, value, selected) { | |
return $('<option>'). | |
attr('value', value). | |
attr('selected', selected). | |
text(text); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment