Aflred
Aflred

Reputation: 4603

bootstrap selectpicker knockoutjs disable option

I have the following binding in js fiddle.

<div class="container body-content">
    <div>Name : <span data-bind="text: Name"></span>
    </div>The select control should be below
    <select multiple data-bind="selectPicker: teamID, optionsText: 'text', optionsValue : 'id', selectPickerOptions: { optionsArray: teamItems, disabledOption: IsDisabled }"></select>
    <div>Selected Value(s)
        <div data-bind="text: teamID"></div>
    </div>
</div>

I am thinking of doing this disabledOption: IsDisabled and then adding

this.teamItems = ko.observableArray([{
         text: 'Chris',
         id: 1,
         IsDisabled: false
     }, {
     text: 'Peter',
     id: 2,
     IsDisabled: false
 }, {
     text: 'John',
     id: 3,
     IsDisabled: false

 }]);

I would like to know how to disable an option in the select.

Upvotes: 0

Views: 561

Answers (1)

user3297291
user3297291

Reputation: 23397

In the knockout docs, there's an example that shows how you can disable an item using an optionsAfterRender method.

About the method you can pass to it:

  • It has to be in your viewmodel, not in your items
  • It takes in the option HTML node, and the item it's bound to

So step one is to find a place to store which items are disabled. The easiest option would be to store it inside your teamItems' objects:

{
  text: 'Chris',
  id: 1,
  disable: ko.observable(true)
}

Now, we need to add a method that takes in an item and creates a binding. We can take this straight from the example:

this.setOptionDisable = function(option, item) {
  ko.applyBindingsToNode(option, {
    disable: item.disable
  }, item);
}

Finally, we need to tell knockout to call this method:

<select multiple data-bind="optionsAfterRender: setOptionDisable, ...

Note that after changing a disable property in one of your items, you'll have to call teamItems.valueHasMutated manually.

Here's an updated fiddle:

http://jsfiddle.net/nq56p9fz/

Upvotes: 1

Related Questions