JSFiddle - React, Tailwind, and code Playground
HTML
<div class="example">
<div class="block red">
<h2>Manual Options</h2>
<p>In this test, select options are added manually within a foreach construct. Select works as expected, but initial value of observable is cleared.</p>
<select data-bind="value: ChoiceA">
</select>
<p>ChoiceA = [<span data-bind="text: ChoiceA"></span>]</p>
</div>
<div class="block green">
<h2>Binding Options</h2>
<p>In this test, select options are added using options binding. Select works as expected and initial value of observable is kept.</p>
<select data-bind="options: Choices, optionsText: 'Name', optionsValue: 'Id', value: ChoiceB"></select>
<p>ChoiceB = [<span data-bind="text: ChoiceB"></span>]</p>
</div>
</div>
CSS
.example {
font-family: sans-serif;
}
.block {
width: 40%;
float: left;
padding: 0 10px;
margin: 10px;
}
.red {
background-color: #F0A8A8;
border: 1px solid red;
}
.green {
background-color: #AAF0A8;
border: 1px solid green;
}
.clear {
clear: both;
}
JavaScript
var model = {
// Store the selection here. Initialised to 3. This selects
// the correct option, but the value then disappears until a
// new selection is made.
"ChoiceA": ko.observable(3),
// Store the selection here. Initialised to 3. This selects
// the correct option, and the value stays as expected.
"ChoiceB": ko.observable(3),
// The options
"Choices": ko.observableArray([
{ Id: 1, Name: "Option1" },
{ Id: 2, Name: "Option2" },
{ Id: 3, Name: "Option3" }])
};
ko.applyBindings(model);