Ryan
Ryan

Reputation: 4414

KnockoutJS "checked" binding doesn't work with observableArray and radio button lists

I have an observableArray called SelectedAttributeValueIds which I need to be bound to a radio button list using the "checked" binding. e.g.

<input type="radio" data-bind="checked: SelectedAttributeValueIds" />

However KnockoutJS is replacing the observableArray with a single value that is just observable. so instead of the SelectedAttributeValueIds having a value of [123] it will be "123"

I did this as a workaround but was wondering if there is an easier way:

<input type="radio" data-bind="event: { change: function() { $parent.SelectedAttributeValueIds([$data.ID()]); } }" />

Upvotes: 1

Views: 2936

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

For radio buttons, KO assumes that there will only be one "value" to write. For checkboxes, it would add/remove values from the array.

It sounds like you want to always write a single value, but have it be in an array as the only element.

One option would be to create a ko.computed to represent the item in an array. Another option would be to use a writeable ko.computed to bind against the input and have it broker the value between the formats that you want. Something like:

this.SelectedAttributeValueIds = ko.observableArray();
this.SelectedAttributeValueId = ko.computed({
   read: function() {
       var values = this.SelectedAttributeValueIds();
       return values.length ? values[0] : [];
   },
   write: function(newValue) {
       this.SelectedAttributeValueIds([newValue]);
   },
   owner: this
});

Upvotes: 2

Related Questions