I have the following issue:
I have an observable array of objects in the format { isSelected: false, Message: "Test1" }, { isSelected: true, Message: "Test2"}. I am generating a select list in the view from this observable array. I want the value with the property isSelected = true to be preselected ( that will be: Message: “Test2” in this example). Here is my code:
Knockout:
function ViewModel()
{
this.DummyOptions = ko.observableArray([{ isSelected: false, Message: "Test1" }, { isSelected: true, Message: "Test2"}]);
this.selectedValue = ko.observable();
}
ko.applyBindings(new ViewModel());
Html:
<div>
Dummy
<select id="dummy" data-bind="options: DummyOptions, optionsText: 'Message'"></select>
</div>
Fiddle: http://jsfiddle.net/PsyComa/RfWVP/52/
I believe this will be simple but I am very new to knockout and I was not able to make it work as expected. Any help with working code will be greatly appreciated. Thank You.
You’re right, this is indeed very simple with knockout.js.
An observable can be bound to the currently selected option using the “value” binding:
Now, just use the object with “isSelected == true” as the initial value of this observable:
http://jsfiddle.net/RfWVP/54/