Normally when I have a select list I bind it with knockout like this:
<select
data-bind="
options: data,
optionsText: 'Name',
optionsValue: 'Id',
optionsCaption: 'Select ...',
value: dataSelectedId" ></select>
But there's a problem with such binding: you do not have the selected object. You have its ID instead. How to merge this two requirements: have binding to both item's id and item itself?
Right now I use computed
observable to get selected item, which usually looks like this:
self.dataSelectedCO = ko.computed(function() {
for (var i = 0; i < self.data().length; ++i)
if (self.data()[i].Id() == self.dataSelectedId())
return self.data()[i];
});
I've tried to wrap value getter using a custom function but it's called for every element when selection changes, so there are no benefits here of using this approach. Here's a jsfiddle.
Remove the optionsValue
parameter. Then the selected value will be the 'selected item' instead of the Id
.
The updated code will be:
<select
data-bind="
options: data,
optionsText: 'Name',
optionsCaption: 'Select ...',
value: dataSelectedItem" ></select>
dataSelectedItem
will now have the selected item.
Once you have the item. you can get the Id
from the object itself like dataSelectedItem().Id
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