I am trying to bind a select with KnockoutJS to a predefined value that comes from my model. According to the documentation this should come from the value property but I am not able to preselect a value in the dropdown based on this. Here is sample code that reflects the issue that I have:
<script src="Scripts/jquery-1.7.1.js"></script>
<script src="Scripts/knockout-2.0.0.js"></script>
<script>
$(function () {
var viewModel =
{
Positions: ko.observableArray(
[
{ Id: 1, PositionName: 'Point Guard' },
{ Id: 2, PositionName: 'Shooting Guard' },
{ Id: 3, PositionName: 'Center' },
{ Id: 4, PositionName: 'Small Forward' },
{ Id: 5, PositionName: 'Power Forward' }
]),
Players: ko.observableArray(
[
{ Id: 1, Name: 'Derrick Fisher', Position: 'Point Guard' },
{ Id: 2, Name: 'Kobe Bryant', Position: 'Shooting Guard' },
{ Id: 3, Name: 'Andrew Bynum', Position: 'Center' },
{ Id: 4, Name: 'Metta World Peace', Position: 'Small Forward' },
{ Id: 5, Name: 'Pau Gasol', Position: 'Power Forward' }
])
};
ko.applyBindings(viewModel);
});
</script>
In my bindings I would like to use a simple table where the first column has preselected the lookup value, in this case the “position” of the player by default. Here is an example:
<table>
<thead>
<tr>
<td>Position</td>
<td>Player</td>
</tr>
</thead>
<tbody data-bind='foreach: Players'>
<tr>
<td>
<select data-bind="options: $root.Positions, optionsText:'PositionName',
value:'$data.Position', optionsCaption: 'Choose...'">
</select>
</td>
<td>
<span data-bind='text: Name'></span>
</td>
</tr>
</tbody>
</table>
The lookups seem to bind okay (the select is populated with all the position values in lookup) however the given player’s position is not selected by default. Can anyone spot where I’ve made a bad assumption or error?
When you do not use
optionsValue, then it will write the selected object to what you have bound tovalue.If your
playerhas a separate copy of thepositionobject, then it will not match.For example,
So, your player’s either need to use a reference to the same object or you should specify the
optionsValuebinding withId, so that it reads/writes the Id to the player’s position property.