1

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.

Community
  • 1
  • 1
Craig
  • 36,306
  • 34
  • 114
  • 197

1 Answers1

1

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>

Fiddle Demo

Akhlesh
  • 2,389
  • 1
  • 16
  • 23
  • This fiddle demo does not work as expected. The second service in the list displays 'One' when it should display 'Two'. – Craig Aug 05 '14 at 22:22
  • Sorry thats my mistake. you need to provide value binding in option then it will work as expected. see updated fiddle. – Akhlesh Aug 06 '14 at 01:38