Tumo Maraisane
Tumo Maraisane

Reputation: 105

Dropdown multiselect not showing when values set in javascript append

I have a multiselect dropdown that shows options when I hard code them, but as soon as I get my values from the database and append them to the options it does not show. Is there another way to show these values?

Scripts:

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src = "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js">
    </script>
    <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css"/>
</head>

Select dropdown which shows dropdown values:

<div class="col-sm-4">
    <select class="form-control" id="multiselectpuc" multiple="multiple">
        @*<option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>*@
    </select>
</div>

Appending data to the dropdown:

$('#multiselectstudent').multiselect({
    buttonWidth: '285px',
    allSelectedText: 'All',
    includeSelectAllOption: true,
    nonSelectedText: 'select puc',
});

$.ajax({
    type: "GET",
    url: '@Url.Action("GetStudents", "Home")',
    datatdataType: 'json',
    contentType: 'application/json',
    success: function (data) {
        data.data.forEach(function (item) {
            console.log(item.id)
            //$('#multiselectstudent').append("<option value='" + item.id + "'>" + item.code+ "</option>");
            $("#multiselectstudent option[value='" + item.id + "']").prop("selected", true);
        });
});

item.data has values in console, I can also see the values set in the elements tab, but the dropdown does not show. Please see image: enter image description here

Upvotes: 1

Views: 5112

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

UI wrappers over a <select> will generally not update themselves when you change the underlying select and will need additional code.

In the case of , after changing the underlying select you need to call

$("#selectid").multiselect("rebuild");

https://davidstutz.github.io/bootstrap-multiselect/#getting-started

Rebuilds the whole dropdown menu. All selected options will remain selected (if still existent!).

Upvotes: 2

Related Questions