如何 customize/convert bootstrap multiselect 到单个 select 有条件地 w/o 单选按钮

How to customize/convert bootstrap multiselect to single select conditionally w/o radio buttons

HTML如下:-

<select name="companyName"  id="ddlCompanyId" name="companyList" multiple="multiple" ></select>

我正在使用 bootstrap-multiple.js 并且有条件地想使用没有单选按钮的单个 select。

提前致谢!

为了 remove/hide 单选按钮,您可以在 css 中添加新样式,或者您可以使用以下事件:

onDropdownShown: A callback called after the dropdown has been shown.

要从多选更改为单选,只需切换 html 属性 multiple="multiple"rebuild 插件即可。

来自评论:

and how to clear selection on single select dropdown with bootstrap multiselect?

multiple: ....using the plugin for single selections (without the multiple attribute present), the first option will automatically be selected if no other option is selected in advance.

这意味着:您需要使用 jQuery .val() 和空字符串来取消选择每个选项。

$('#ddlCompanyId').multiselect({
    onDropdownShown: function(e) {
        if (this.options.multiple == false) {
            this.$container.find(':radio').hide();
        }
    }
});

$('#btnToggle').on('click', function(e) {
    $('#ddlCompanyId').attr('multiple', function(idx, attr) {
        return (attr==undefined) ? 'multiple' : null;
    });
    // deselect ...
    $('#ddlCompanyId').val('');
    // rebuild the whole dropdown...
    $('#ddlCompanyId').multiselect('rebuild');
});


$('#btnToggleDisable').on('click', function(e) {
    if ($('#ddlCompanyId').is(':disabled')) {
        $('#ddlCompanyId').multiselect('enable');
    } else {
        $('#ddlCompanyId').multiselect('disable');
    }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css">
<script src="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"></script>



<div class="container">
    <div class="row">
        <select id="ddlCompanyId" multiple="multiple">
            <option value="cheese">Cheese</option>
            <option value="tomatoes">Tomatoes</option>
            <option value="mozarella">Mozzarella</option>
            <option value="mushrooms">Mushrooms</option>
            <option value="pepperoni">Pepperoni</option>
            <option value="onions">Onions</option>
        </select>
        <button class="btn btn-primary" type="button" id="btnToggle">Toggle Multiselect</button>
        <button class="btn btn-primary" type="button" id="btnToggleDisable">Toggle disable</button>
    </div>
</div>