如果尚不存在从引导选择中添加选项的方法?

问题描述 投票:0回答:2

我正在使用bootstrap-select

如果我在通过select获得的搜索菜单中找不到该新选项,该如何将其添加到data-live-search="true"中呢?

jquery jquery-ui jquery-plugins bootstrap-selectpicker
2个回答
2
投票

请遵循以下代码::

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链接:https://jsfiddle.net/ktmv1vxh/1/


0
投票

正在发布此改进的答案,希望对其他人有所帮助像往常一样使用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

© www.soinside.com 2019 - 2024. All rights reserved.