montisqu
montisqu

Reputation: 3

Radio button set property of parent object with selected object

Javascript:

functional OrderViewModel() {
   this.selectedVehicle = ko.observable();

   this.vehicles = ko.observableArray([
    new VehicleViewModel('Toyota'),
    new VehicleViewModel('Ford'),
    new VehicleViewModel('Chevy')
   ]);
}


function VehicleViewModel(name) {
   this.name = name;
}


ko.applyBindings(new OrderViewModel());

Html:

<div>
    <!--ko foreach: $data.vehicles -->
        <label>
            <input type="radio" data-bind="value: $data.name, checked: $parent.selectedVehicle" />
            <span data-bind="text: $data.name"></span>
        </label>
    <!-- /ko -->
</div>

How do I make it update the "selectedVehicle" property of the OrderViewModel with the selected VehicleViewModel (instead of just the name)?

Upvotes: 0

Views: 152

Answers (1)

QBM5
QBM5

Reputation: 2788

You basically had it. Look at this https://jsfiddle.net/16hozLzL/

<div>
    <!--ko foreach: $data.vehicles -->
        <label>
            <input type="radio" data-bind="value: $data, checked: $parent.selectedVehicle" />
            <span data-bind="text: $data.name"></span>
        </label>
    <!-- /ko -->
</div>

Just remove the .name from the values binding and it will bind the entire object

Upvotes: 2

Related Questions