Basically, the code converts a large select list with optgroups into a more user-friendly tabbed Twitter-bootstrap component.
I'm not sure how much into detail I need to get but on GitHub I uploaded a working example. This is the first time I write a jquery plugin and any advise is welcome.
(function($) {
$.fn.bootstrapSelect = function(options) {
//Extend default options with those provided.
var opts = $.extend({}, $.fn.bootstrapSelect.defaults, options);
var topLevel='';
var subLevel='';
var selectedValue ='';
var sectionActive = false;
var selected = '';
// Rewrite the info in the select box
$('optgroup',this).each(function(x) { //for each optgroup
//get section label
var sectionLabel = $(this).attr('label');
//get section content
var sectionContent = '';
$('option',this).each(function(x) {
/*Check if an option is selected, and set section active*/
if ($(this).attr('selected')) {
selectedValue = $(this).attr('value');
sectionActive = true;
}
sectionContent += '<a ';
$(this).attr('selected') ? sectionContent += 'class="bsactive" ' : '';
sectionContent += 'value="' + $(this).attr('value') + '">' + $(this).text() + '</a>\n';
});
sectionActive ? selected = true : false;
topLevel += '<li';
sectionActive ? topLevel += ' class="active"' : '';
topLevel += '><a href="#optgroup' + x + '" data-toggle="tab">' + sectionLabel + '</a></li>\n';
subLevel += '<div id="optgroup' + x + '" class="tab-pane';
sectionActive ? subLevel += ' active' : '';
subLevel += '">\n' + sectionContent + '</div>\n';
sectionActive = false;
});
//Replacement tabbed select
var tabbedselect = '<div class="tabbable '+opts.position+'">\n';
if ( opts.position != "tabs-below") tabbedselect += '<ul class="nav nav-tabs">\n'+topLevel+'</ul>\n';
tabbedselect += '<div class="tab-content">\n'+subLevel+'</div>\n'
if ( opts.position == "tabs-below") tabbedselect += '<ul class="nav nav-tabs">\n'+topLevel+'</ul>\n';
tabbedselect += '</div>\n';
// Replace the select with the tabbed menu
this.replaceWith(tabbedselect);
// Add hidden input field with the selected value
$("form").append('<input type="hidden" name="'+opts.inputId+'" id="'+opts.inputId+'" value="'+selectedValue+'" />');
//set first tab and content area active if nothing is selected
if (selected == false) {
$("div.tab-content div:first-child").addClass("active");
$("ul.nav-tabs li:first-child").addClass("active");
}
// set input field value on click
$(".tab-content a").click(function () {
$("*").removeClass("bsactive");
$(this).addClass("bsactive");
$('input#'+opts.inputId).attr('value', $(this).attr('value'));
})
};
//default settings
$.fn.bootstrapSelect.defaults = {
'position' : 'tabs-left',
'inputId' : 'bootstrap-select'
};
})(jQuery);