get selected option text in knockout

后端 未结 3 1788
情歌与酒
情歌与酒 2020-12-19 02:50

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 ?

<
相关标签:
3条回答
  • 2020-12-19 03:29

    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);
    
    0 讨论(0)
  • 2020-12-19 03:36

    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

    0 讨论(0)
  • 2020-12-19 03:47
    vm.selectedCountryName = ko.computed(function () {
            var text = '';
            ko.utils.arrayForEach(vm.countries(), function (item) {
                if (item.CountryId == vm.selectedCountry()) {
                    text = item.CountryName;
                    return;
                }
            });
            return text;
        });
    
    0 讨论(0)
提交回复
热议问题