Nate
Nate

Reputation: 2326

Setting the initial value in a Knockout select

I'm having problems getting the initial value of a select to be equal to the value in my knockout model.

http://jsfiddle.net/npearson99/bjwAT/2/

In that fiddle, the group should be "Group 2", but it's not selecting any group.

If I change value: 'SelectedGroupId' to value: 2, it works.

<div data-bind="with: selectedWorkout">
 <h3>Current Workout</h3>
Workout Id:
<label data-bind="text: Id"></label>
<br/>Workout Name:
<label data-bind="text: Name"></label>
<br/>Group:
<select data-bind="options: $root.groupList, 
                          optionsText: 'GroupName',
                          optionsValue: 'Id',
                          optionsCaption: 'No Group',
                          value: 'SelectedGroupId'"></select>

function Group(Id, GroupName) {
    var self = this;

    self.Id = Id;
    self.GroupName = GroupName;
}

function Workout(id, name, selectedGroupId) {
    var self = this;
    self.Id = id;
    self.Name = name
    self.SelectedGroupId = ko.observable(selectedGroupId);
}

function viewModel() {
    var self = this;

    self.groupList = ko.observableArray([
    new Group(1, 'Group One'),
    new Group(2, 'Group Two'),
    new Group(3, 'Group Three')]);

    self.selectedWorkout = ko.observable(new Workout(4, 'Test Workout', 2));
}

ko.applyBindings(new viewModel());

Upvotes: 0

Views: 164

Answers (1)

nemesv
nemesv

Reputation: 139748

The value binding takes a reference to the property as a parameter and not a string (so not the property name like the optionsValue or optionsValue).

So the correct usage is:

<select data-bind="options: $root.groupList, 
                      optionsText: 'GroupName',
                      optionsValue: 'Id',
                      optionsCaption: 'No Group',
                      value: SelectedGroupId"></select>

Demo JSFiddle.

Upvotes: 1

Related Questions