The jQuery Chosen plugin is great for single and multi select fields. It not only makes them searchable but also gives a much needed user interface to multi selects. In a recent implementation for a multi select I had a list that included optgroups. The optgroups were each rather lengthy and I was asked if it was possible to make them expand and contract. After a bit of research I was able to and I even snuck in a font awesome icon to indicate the state to make the UI a bit more obvious. Here is the snippet, enjoy!
$(".chosen-select").chosen({
disable_search_threshold: 5
});
$('.chosen-select').on('chosen:showing_dropdown', function(evt, params) {
$('.group-result').each(function(key, group) {
$(group).append(' <i class="fa fa-sort-up">');
$(group).nextUntil('.group-result').each(function(key, item) {
$(item).hide();
});
});
});
$('body').on('click', '.group-result', function() {
icon = $(this).find('i');
if(!icon) {
$(this).append(' <i class="fa fa-sort-up">');
}
if($(icon).hasClass('fa-sort-up')) {
$(icon).removeClass('fa-sort-up');
$(icon).addClass('fa-sort-down');
}
else if($(icon).hasClass('fa-sort-down')) {
$(icon).removeClass('fa-sort-down');
$(icon).addClass('fa-sort-up');
}
$(this).nextUntil('.group-result').each(function(key, item) {
if(!$(item).hasClass('result-selected')) {
$(item).toggle();
}
});
});