DanScan
DanScan

Reputation: 901

How to set the checkbox values when in an observableArray

I have an observableArray of items that I mapped to a list of checkboxes. They start off as all being unclicked. But when a particular item is selected I want a set of checkboxes to become checked.

My Viewmodel:

       function ModelView(data) {
            var self = this;

            self.Items= ko.observableArray(data.Items);
            self.ItemOptions = ko.observableArray(data.ItemOptions ); 

            self.PreSelectOptions = function(item){
                ko.utils.arrayForEach(self.ItemOptions(), function (itemoption) {
                var selected = false;
                //Loop through the options the item has and preselect the checkboxes
                for (var i = 0; i < item.Option.length; i++) {
                    if (itemoption.ID == item.Option[x]) {
                        selected = true;
                        break;
                    }
                }

                itemoption.chosen = selected;//Check the checkbox
            }); 


       }

Html snippet:

       <ul data-bind="foreach: channels">
          <li>
              <input type="checkbox" data-bind='checked: chosen' /><span data-bind="text: ChannelName"></span></li>
       </ul>

I have stepped through the code and itemoption.chosen is being set to true. Do I have to rebind the checkboxes?

Upvotes: 0

Views: 569

Answers (1)

Cyanfish
Cyanfish

Reputation: 4163

The issue is that chosen is not an observable. The binding won't update automatically when bound to a non-observable.

You could make it an observable with code like this run after setting self.ItemOptions:

ko.utils.arrayForEach(self.ItemOptions(), function (itemoption) {
    itemoption.chosen = ko.observable(itemoption.chosen);
});

However, since self.ItemOptions is a shallow copy of data.ItemOptions, the data object's item options will also be modified to use the observable. A better option might be to use the ko.mapping plugin:

self.ItemOptions = ko.mapping.fromJS(data.ItemOptions);

In either case, you'll need to change your syntax to reference chosen as an observable:

itemoption.chosen(selected); // Check the checkbox

Upvotes: 1

Related Questions