Similar question as: Select element's initial value
I'm having an issue setting the initial value of the select element. I basically have a list of seed data coming in from the server to populate the drop down list, and I want the selected value to represent what should be selected from the entity.
Because the data model's selected value doesn't equal the object reference in the seed data, nothing is selected.
Right now, I'm looping through each entity, finding the correct selected value, setting that equal to the seed data's equivalent, then Knockout knows how to wire it up.
Is there a more elegant solution that this? I fiddled a simplified example with more details... http://jsfiddle.net/hbrYM/14/
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .
Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.
As you correctly guessed the selectedValue reference doesn't match so KO doesn't select that item. The way to get this to work is to not save the complex object in the selected value and instead select the ID, as a primitive type equality can succeed and the correct value is selected.
http://jsfiddle.net/VLTFB/3/
You'll need to use the optionsValue option on the options binding (if that makes sense :)
<select data-bind="options: seedData,
optionsText: 'firstName',
optionsValue: 'ID',
value: data.selectedValue">
EDIT
As discussed you can reselect the correct item with a computed (untested).
vm.currentlySelected = ko.computed(function () {
for (var i = 0; i < this.seedData().length; i += 1) {
var data = this.seedData()[i];
if (data.ID === this.selectedValue()) {
return data;
}
}
return null;
}, vm);
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With