Bootstrap-select DropDownList not showing

2019-09-06 02:15发布

问题:

I have a bootstrap-select combobox that I fill with data in an ajax call Html:

<div class="row">
<select id="selectGemeente1" class="selectpicker" data-live-search="true"></select>
</div>

Ajax call:

var gemeenteLijst = [];

var GetGemeentes = function () {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: 'https://localhost::blabla',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            var test = document.getElementById("selectGemeente1");
            data.forEach(function (item) {
                var opt = document.createElement("option");
                opt.value = item.GemeenteId;
                opt.innerHTML = item.Naam;
                test.appendChild(opt);
            });         
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

$(document).ready(function () {
    GetGemeentes();  
})

After running my application, my select is filled but the dropdown is not opening..

html after run

I have seen a lot of solutions saying that I should put this in my $(document).ready

$(".selectpicker").html(optgroup);

but then I get an error saying that .selectpicker is not a function.

gemeenteLijstLaden.js:36 Uncaught TypeError: $(...).selectpicker is not a function

I have implemented these script files

<script src="~/Scripts/jquery-2.2.3.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/i18n/defaults-nl_NL.min.js"></script>
<script src="~/Scripts/myCharts/gemeenteLijstLaden.js"></script>

回答1:

I found a solution. I just needed to refresh my select

$('.selectpicker').selectpicker('refresh');


回答2:

success: function (data) {   
  var selectGemeent = $("#selectGemeente1");
                selectGemeent.empty();
                $('#selectGemeente1').append($("<option></option>").
                                attr("value", "0").
                                text("Select"));
                $.each(data.forEach, function (index, item) {
                    selectGemeent.append($('<option>', {
                        value: item.GemeenteId,
                        text: item.Naam
                    })); ////function
                });
},

use it in you ajax success and add your other fileds after text and value