This is actually related to a question I had asked here. But since, this was in a slightly different context, I thought it was best if I created a new question altogether.
I know how to pre-select an option in the dropdown when I'm working with a simple array of strings.
Array of strings
View
<select id="first" data-bind="options: firstDropdownOptions, value: selectedFirstOptionValue"></select>
View Model
firstDropdownOptions: ko.observableArray(['USA','UK','Other']);
selectedFirstOptionValue: ko.observable('UK');
..but how do I pre-select an option if it's an array of objects?
Array of objects
View
<select id="second" data-bind="options: secondDropdownOptions, optionsText: 'title', value: selectedSecondOptionValue"></select>
View model
secondDropdownOptions: ko.observableArray([
{ value: -1, title: 'Select Type' },
{ value: 1, title: 'Option New 1' },
{ value: 2, title: 'Option New 2' }, // I want this option selected initially
{ value: 3, title: 'Option New 3' }
]);
// similarly, how to pre-select the 3rd option in this case?
selectedSecondOptionValue: ko.observable('')
This is the fiddle here.
I've tried passing the entire object here, the value only as an integer. I even thought maybe if I try to render the <select>
dropdown in a way that I can set the attributes explicitly, then maybe I can try and manipulate the selected
attribute for it. But I did not get the expected results. Here is the fiddle for this.
<select data-bind="foreach: secondDropdownOptions">
<option data-bind="attr: { text: title, value: value}"></option>
</select>
In this case, the text does not bind, although the value attribute binds to each <option>
in the dropdown.