Skip to content Skip to sidebar Skip to footer

Knockout - Applying Styles To The Selected Item In A Bootstrap Select

So this is piling libraries on top of libraries, but I'm not sure what else to do. Our application has a number of drop-down elements all of which are Bootstrap Select objects. The

Solution 1:

You could try to fix this by preventing the post-processing of the options:

  1. Replace the options binding with a foreach binding in the select element, binding each option with the appropriate ko-bindings.
  2. Make sure the selectPicker binding has its descendant bindings bound before calling selectpicker on the element.
  3. Profit!

ko.bindingHandlers['selectPicker'] = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
      ko.applyBindingsToDescendants(bindingContext, element);
      $(element).selectpicker();
      return { controlsDescendantBindings: true };
    }
}

ko.applyBindings({
    selectedValue: ko.observable(3),
    options: [
      { id: 1, name: 'Mustard', dc: '<span class="badge badge-warning">Mustard</span>' },
      { id: 3, name: 'Ketchup', dc: '<span class="badge badge-danger">Ketchup</span>' },
      { id: 4, name: 'Relish', dc: '<span class="badge badge-success">Relish</span>' }
    ]
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><linkhref="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script><scriptsrc="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script><linkhref="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.3/css/bootstrap-select.min.css"><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.3/js/bootstrap-select.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script><selectdata-bind="selectPicker, value: selectedValue"><!-- ko foreach: options --><optiondata-bind="text: name, attr: { value: id, 'data-content': dc }"></option><!-- /ko --></select>

Post a Comment for "Knockout - Applying Styles To The Selected Item In A Bootstrap Select"