Naor
Naor

Reputation: 24063

Bootstrap drop down does not select the element. need drop down with button group design

I am using twitter bootstrap and looking for a drop down that will look like a button group. The problems are that in all the twitter bootstrap example, the drop down is only act as a menu item so the selected item is not really changed:
http://twitter.github.com/bootstrap/javascript.html#dropdowns

Does anyone have idea how can I design drop downs like the button group?

Upvotes: 3

Views: 2788

Answers (1)

Naor
Naor

Reputation: 24063

I convert this web finding to a jquery plugin:

(function($) {
    $.fn.buttonSelect = function() {
        this.hide().wrap('<div class="btn-group"/>');
        var select = this.parent();
        var selectedOption=this.find('option[selected]').length>0?this.find('option[selected]'):this.find('option:nth(0)');
        var currentValue = selectedOption.val();
        var currentText = selectedOption.text();
        select.html(
            '<input type="hidden" value="' + this.val() + '"/>'+
            '<a class="btn dropdown-toggle" data-toggle="dropdown" href="javascript:;">'+
                '<span>'+currentText+'</span>'+
                '&nbsp;&nbsp;<span class="caret"></span>'+
            '</a>'+
            '<ul class="dropdown-menu"></ul>');

        var dropdownMenu=select.find('.dropdown-menu');
        this.find('option').each(function(o, q) {
            dropdownMenu.
                append('<li><a href="javascript:;" data-value="' + $(q).attr('value') + '">' + $(q).text() + '</a></li>');
        });

        var hidden=select.find('input[type=hidden]');
        var label=select.find('.btn span:nth(0)');
        dropdownMenu.find('a').click(function() {
            hidden.val($(this).data('value')).change();
            label.text($(this).text());
        });

        return this;
    };
})(jQuery);

Then, using $(elem).buttonSelect(); makes the select element look like the button group .

Upvotes: 3

Related Questions