rubenfa
rubenfa

Reputation: 851

Option not being disabled when I use optionsCaption

I'm trying to disable options in a combobox with knockout.js. In knockout documentation there is one example:

<select data-bind=" options: myItems, optionsText: 'name', optionsValue: 'id',
optionsAfterRender: setOptionDisable"> </select>

var vm = { myItems: [{ name: 'Item 1', id: 1, disable: ko.observable(false) }, { name: 'Item 3', id: 3, disable: ko.observable(true) }, { name: 'Item 4', id: 4, disable: ko.observable(false) }], setOptionDisable: function(option, item) { ko.applyBindingsToNode(option, { disable: item.disable }, item); } }; ko.applyBindings(vm);

It works well. Here is the JSFiddle.

But when I add optionsCaption, bindings are not working, and only caption is shown in combobox. Here is the JS Fiddle with captionsOption.

What is happening?

Upvotes: 2

Views: 454

Answers (1)

user3297291
user3297291

Reputation: 23397

When knockout inserts a caption, it uses the value undefined for the option that shows the caption.

This means that, in your after render, you'll get the first item as undefined. Since you cannot apply the data-bind disable: undefined.disable, it will throw an error.

You'll need an extra check to prevent knockout from trying to bind to undefineds disable property:

setOptionDisable: function(option, item) {
  if (!item) return;
  ko.applyBindingsToNode(option, {
    disable: item.disable
  }, item);
}

Upvotes: 1

Related Questions