knockout radio group binding to an observableArray

1.7k Views Asked by At

I have a view model which contains an array of my objects. one property of my object is a boolean value called minversion to which i want to bind to a radio group. I have tried a few methods and can not get this to work.

Here is my view model

  function ViewModel() {

   var self = this;
   this.apps = ko.observableArray(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));

};

Here are my inputs

  <tbody data-bind="foreach: apps">
                            <tr>
                                <td style="text-align:center">

                                    <input type="radio" name="apps" data-bind="attr: { value: Id }, checked: MinVersion" />


                                </td>
                                <td data-bind="text: type"></td>
                                <td data-bind="text: Name"></td>

                            </tr>

                        </tbody>
1

There are 1 best solutions below

0
On

If you are using the radio button as intended (one value selected at a time), then the checked value will need to be outside of the apps collection. If you are trying to use it like a checkbox array (0 - many selected at a time), then having the checked value inside the collection is appropriate.

Here is a working example of a dynamically generated radio button array: http://jsfiddle.net/74ht766s/1/

<div data-bind="foreach: apps">
    <input type="radio" name="apps" data-bind="attr: { value: $data}, 
        checked: $parent.selectedVersion,"/>
    <span data-bind="text: 'Version ' + $data"/>
    <br/>
</div>

var ViewModel = function() {
    var self = this;

    self.apps = [1,2,3];
    self.selectedVersion = ko.observable(self.apps[0].toString());
};