Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get selected option text in knockout

I am using knockoutjs to bind a select list. Here is a Sample , I want to get selected option text instead of selected value.

How to get it using knockoutjs ?

<select id="projectMenu" name="projectMenu" data-bind="   
        value: selectedProject,
        options:        projectFilters,
        optionsText:    'a', 
        optionsValue:   'b',   
        optionsCaption: '-- Select Project --'
    ">
    </select>
<b>Selected Project:</b> <span data-bind="text: selectedProject"></span>
like image 619
Sudarshan Avatar asked Oct 24 '13 09:10

Sudarshan


2 Answers

The simplest way to do it is to remove the optionsValue binding. When you don't sepcify the optionsValue binding, the entire item will be the selected value.

<select id="projectMenu" name="projectMenu" data-bind="   
        value: selectedProject,
        options:        projectFilters,
        optionsText:    'a',         
        optionsCaption: '-- Select Project --'
    ">
    </select>
<b>Selected Project:
<span data-bind="text: selectedProject() ? selectedProject().a : 'no selection '"></span>

See fiddle

like image 180
Damien Avatar answered Oct 09 '22 07:10

Damien


As far I am concerned it is not possible with just a simple binding. But You can easily create computedObservable which choose optionText based on optionValue

vm.selectedOption= ko.computed(function () { 
   for (var i = 0; i < this.projectFilters().length; i += 1) {
       var data = this.projectFilters()[i];
       if (data.a === this.selectedProject()) {
           return data.b;
       }
   }
   return null;
}, vm);
like image 21
Krzysztof Cieslak Avatar answered Oct 09 '22 07:10

Krzysztof Cieslak