简体   繁体   中英

Bootstrap dropdown as select option

How do you make a bootstrap dropdown act like an HTML select option? I recently had this problem. I partially think the Bootstrap is missing this feature in the core library, but the team must have their reason for not including it in the library.

This is my first time posting a Q&A question . If this doesn't look like a question, I'm sorry.

Here are the extended methods:

$.fn.extend({
    dropdownConvert: function(b) {
        b = b || true;
        console.log(b);
        this.each(function(){
            var $this = $(this);
            if ($this.prop("tagName") == "SELECT" && typeof $this.attr("id") == "string" && $this.find("option").length > 0) {
                var temp = '<div class="dropdown" id="' + $this.attr("id") + '"><button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"><span class="selected">' + $this.find("option")[0].innerHTML + '</span> <span class="caret"></span></button><ul class="dropdown-menu">';
                var o = $this.find("option");
                for (var i = 0; i < o.length; i++) {
                    temp += '<li><a>' + o[i].innerHTML + '</a></li>';
                }
                temp += '</ul></div>';
                $this[0].outerHTML = temp;
                if (b)
                    $("#"+$this.attr("id")).dropdown();
            }
        });
    },
    dropdown: function(cb) {
        console.log($(this));
        this.each(function(){
            var $drop = $(this);
            $drop.find("a").bind("click", function(){
                var selected = $(this).text();
                $drop.find(".selected").text(selected);
                $drop.attr("data-selected", selected.toLowerCase());
                if (typeof cb === "function") {
                    cb.call($drop, selected.toLowerCase());
                }
            })
        });
        return this;
    },
    dropdownVal: function(v) {
        var $drop = $(this).first();
        if($drop.hasClass("dropdown")) {
            if (v !== undefined) {
                v = String(v);
                var c = String(v+" ")[0].toUpperCase() + v.substring(1,v.length);
                $drop.attr("data-selected", v);
                $drop.find(".selected").text(c);
            } else {
                if ($drop.data("selected") !== undefined) {
                    return $drop.attr("data-selected");
                } else {
                    return $drop.find(".selected").text();
                }
            }
        } else {
            return undefined;
        }
    }
});

$(elem).dropdownConvert();

This will convert your <select> <option> elements to a bootstrap dropdown. The element must have an id else the function will not run properly.

Arguments: b : Boolean, default - true. Set to false to stop elements from attaching the dropdown click event. If unset, the code will run $(elem).dropdown() after conversion.

$(elem).dropdown();

This will make the bootstrap downdowns behave as <select> <option> elements. The button text will change to the last item you've clicked.

Arguments: cb : function. This is the callback function. The called argument for cb() is the selected item.

$(elem).dropdownVal();

This is similar to the $(elem).val() for input elements. The selected item will return. $(elem).dropdown() needs to be run prior to calling this method.

Arguments: value : will be converted to text. If the argument is anything other than undefined , it will set the current selected option as the value provided regardless of whether it is one of the default options in the select. Leaving it blank will return the selected value.


Auto convert to Bootstrap-styled dropdown when page loads

$(function(){
    $("select").dropdownConvert();
})

Demo

 $.fn.extend({ dropdownConvert: function(b) { b = b || true; console.log(b); this.each(function(){ var $this = $(this); if ($this.prop("tagName") == "SELECT" && typeof $this.attr("id") == "string" && $this.find("option").length > 0) { var temp = '<div class="dropdown" id="' + $this.attr("id") + '"><button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"><span class="selected">' + $this.find("option")[0].innerHTML + '</span> <span class="caret"></span></button><ul class="dropdown-menu">'; var o = $this.find("option"); for (var i = 0; i < o.length; i++) { temp += '<li><a>' + o[i].innerHTML + '</a></li>'; } temp += '</ul></div>'; $this[0].outerHTML = temp; if (b) $("#"+$this.attr("id")).dropdown(); } }); }, dropdown: function(cb) { console.log($(this)); this.each(function(){ var $drop = $(this); $drop.find("a").bind("click", function(){ var selected = $(this).text(); $drop.find(".selected").text(selected); $drop.attr("data-selected", selected.toLowerCase()); if (typeof cb === "function") { cb.call($drop, selected.toLowerCase()); } }) }); return this; }, dropdownVal: function(v) { var $drop = $(this).first(); if($drop.hasClass("dropdown")) { if (v !== undefined) { v = String(v); var c = String(v+" ")[0].toUpperCase() + v.substring(1,v.length); $drop.attr("data-selected", v); $drop.find(".selected").text(c); } else { if ($drop.data("selected") !== undefined) { return $drop.attr("data-selected"); } else { return $drop.find(".selected").text(); } } } else { return undefined; } } }); $(function(){ $("select").dropdownConvert(); $("#t-1").click(function(){ $("#result").text($("#v-1").dropdownVal()); }); $("#t-2").click(function(){ $("#v-1").dropdownVal("melon"); }); })
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <h1>This is a select option:</h1> <select id="v-1"> <option>Apple</option> <option>Orange</option> <option>Banana</option> </select> <button type="button" id="t-1">What is the selected option?</button> <button type="button" id="t-2">Set value to "melon"</button> <p id="result"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM