Skip to content

Instantly share code, notes, and snippets.

@be-mohand
Created June 27, 2019 21:26
Show Gist options
  • Save be-mohand/d1cae3cf538a182e2b48d958c006c45b to your computer and use it in GitHub Desktop.
Save be-mohand/d1cae3cf538a182e2b48d958c006c45b to your computer and use it in GitHub Desktop.
Create a new select dynamically based on the optgroups
$(function() {
if($('select#category-id').length > 0) {
$('select#category-id').each(function() {
var select = $(this),
groupName = 'Choose a category',
optgroups = select.find('optgroup'),
options = select.find('optgroup option'),
groupSelect = $('<select>'),
emptyGroupOption = makeOption(groupName);
groupSelect.
append(emptyGroupOption).
insertBefore(select);
optgroups.each(function(index) {
var optgroup = $(this),
name = this.label,
children = optgroup.children(),
firstChild = children.eq(0),
selected = children.is(':selected'),
groupOption = makeOption(name, index, selected);
groupSelect.addClass('form-control mb-xs').append(groupOption);
children.data('group', index);
firstChild.unwrap();
});
groupSelect.change(function() {
var selectedGroup = parseInt(groupSelect.val(), 10),
optionsInGroup = options.filter(function() { return $(this).data('group') == selectedGroup; }),
hiddenOptions = options.not(optionsInGroup);
hiddenOptions.
attr('selected', false).
detach();
select.append(optionsInGroup);
});
function makeOption(text, value, selected) {
var option = $('<option>');
option.attr('value', value);
option.attr('selected', selected);
option.text(text);
return option;
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment