如果搜索中的 bootstrap-select 选项尚不存在,如何将其添加到该选项?

How to add an option to a bootstrap-select from the search if it does not yet exist?

我正在使用 bootstrap-select

如果我无法在 data-live-search="true" 获得的搜索菜单中找到新选项,我该如何向 select 添加新选项,因为它尚不存在?

请按照以下代码::

HTML

<select class="selectpicker" id="selectpicker" data-live-search="true">
  <option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
  <option data-tokens="mustard">Burger, Shake and a Smile</option>
  <option data-tokens="frosting">Sugar, Spice and all things nice</option>
</select>

CSS

.no-results{
    cursor: pointer;
}

JQUERY

$(document).ready(function (e) {
    $(document).on('click', 'li.no-results', function () {
        var new_option = $(this).text().split('"')[1];
        $("#selectpicker")
       .append('<option>'+ new_option +'</option>')
       .selectpicker('refresh');
       //You can also call AJAX here to add the value in DB
    });
});

请根据需要更改这些代码。
工作 Jsfiddle link:https://jsfiddle.net/ktmv1vxh/1/

我发布了这个改进后的答案,希望它对其他人有所帮助 正常使用 Bootstrap select 只需添加以下

CSS

.comboxme .dropdown-menu .no-results {
        display: none !important;
    }
    .comboxme .dropdown-menu {
        top: unset !important;
        bottom: unset !important;
        padding: 0 !important;
        margin: 0 !important;
        border: 0 !important;
    }
    .comboxme .bs-searchbox {
        padding: 0 !important;
        margin: 0 !important;
        border: 0 !important;
    }
    .comboxme .btn {
        background-color: white;
        color: blue;
    }
    .comboxme .bs-caret {
        color: white;
    }

javascript

$('.selectpicker').selectpicker({
    style: 'btn-info',
    selectOnTab: true,
    size: 6
});

$(function () {
    $(".bs-searchbox input").blur(function () {
        var numberOfActiveItems = $(this).closest(".dropdown-menu").find("li.active").length;
        if (numberOfActiveItems > 0) return;
        console.log(numberOfActiveItems);
        var selectBoxName = $(this).closest(".comboxme").find("select")[0].name;
        $("#" + selectBoxName + " option[value='-1']").remove();
        $("#" + selectBoxName)
            .append('<option value="-1" selected>' + $(this).val() + '</option>')
            .selectpicker('refresh');
        $("#" + selectBoxName + "_add").remove();
        $(this).closest("form").append('<input type="hidden" id="' + selectBoxName + '_add" name="' + selectBoxName + '_add" value="' + $(this).val() + '" />');
    });
});

html

<form>
<select data-width="280px" data-live-search="true" class="selectpicker comboxme form-control" data-val="true" 
data-val-required="The Status field is required." id="Status" name="Status">
<option value="1">Colorado</option>
<option value="2">Connecticut</option>
<option value="3">Delaware</option>
<option value="4">Florida</option>
<option value="6">Georgia</option>
<option value="7">Kentucky</option>
</select>
</form>

示例:https://github.com/codejq/comboxme