Nimish David Mathew
Nimish David Mathew

Reputation: 3168

Bootstrap multiselect not working with knockout binding

I am using this plugin for implementing a multi-select dropdown with checkboxes using KnockoutJs in an ASP.NET MVC web application. I have followed the code in this jsfiddle, but the drop-down is not working whereas the fiddle works fine.

HTML Code:

<select id="status-select" multiple="multiple" class="form-control"
data-bind="options: $root.statuses, selectedOptions: $root.selectedStatuses, multiselect: { includeSelectAllOption: true }">
</select>
...
...
@section require {
    require(['app/viewModel']);
}

<script type="text/javascript">
    $(document).ready(function () {
            $("#status-select").multiselect();
    });
</script>

viewModel.ts:

export class ViewModel {
    statusOptions = [
        "One",
        "Two",
        "Three"
    ];
    statuses = ko.observableArray(this.statusOptions);
    selectedStatuses = ko.observableArray([]);
}

ko.applyBindings(new ViewModel());

The following is the order in which I have included scripts in my project:

<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="~/css/bootstrap-multiselect.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap-multiselect.js"></script>

The following is the output I get:

enter image description here

Please note that the options inside the select tag are bound correctly, but nothing displays in the drop-down since the ul tag is empty. What am I doing wrong here?

Upvotes: 0

Views: 1511

Answers (1)

OfirD
OfirD

Reputation: 10510

That's because you're using Bootstrap 4, while bootstrap-multiselect officialy only works with Bootstrap 3.

That said, there's an open issue on Github named Bootstrap 4 compatibility which requests an official support for Bootstrap 4, and a user named @adeeb1 suggests its own implementation, which works - see it live here.

Few notes:

  • The non-official support for Bootstrap 4 is not perfect, though: in my demo, you can see that the "Select all" checkbox is not aligned with the other checkboxes.
  • My demo uses bootstrap.bundle.min.js, (note the use of bundle), which includes popper.js. Your snippet doesn't uses the bundle version, so either change it, or include a standalone version of popper.js.
  • Your statusOptions property is not an observableArray, and therefore won't utilize two-way binding. I changed it in my demo.
  • No need to use $("#status-select").multiselect(), knockout does it for you.

Upvotes: 1

Related Questions