Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected option Id and value

Tags:

knockout.js

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.

like image 488
SOReader Avatar asked May 07 '13 11:05

SOReader


1 Answers

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

like image 181
ManojRK Avatar answered Oct 13 '22 13:10

ManojRK