Reputation: 36826
I am trying to bind an select with optgroup similar to this question
KnockoutJS - Binding value of select with optgroup and javascript objects
The difference is that there may be one or more selects on the page. So I have something like this.
<script>
var services = ko.observableArray([
{ serviceId: 1 }, { serviceId: 2 }
]);
var servicesList = ko.observableArray([
{ Name: "Group 1", Services: [
{ Id: 1, Name: "One" },
{ Id: 2, Name: "Two" }
]},
{ Name: "Group 2", Services: [
{ Id: 3, Name: "Three" }
]}
]);
</script>
<div class="form-group" data-bind="foreach: services">
<label for="ServiceId" class="control-label col-md-2">Service</label>
<div class="col-md-10">
<select id="ServiceId" name="ServiceId" class="form-control" data-bind="foreach: servicesList, value: serviceId">
<optgroup data-bind="attr: {label: Name}, foreach: Services">
<option data-bind="text: Name, option: Id"></option>
</optgroup>
</select>
</div>
</div>
The problem is the value for each of the selects is not selected.
Upvotes: 1
Views: 457
Reputation: 2399
serviceId is used as value in selectList so it should be observable and servicesList should be used with parent context.
//make observable to keep track selected value
self.services = ko.observableArray([{
serviceId: ko.observable(1)
}, {
serviceId: ko.observable(2)
}]);
//$parent.servicesList
<select id="ServiceId" name="ServiceId" class="form-control" data-bind="foreach: $parent.servicesList, value: serviceId">
<optgroup data-bind="attr: {label: Name}, foreach: Services">
<option data-bind="text: Name,value:Id, option: Id"></option>
</optgroup>
</select>
Upvotes: 1