[英]get selected option text in knockout
I am using knockoutjs to bind a select list. 我正在使用knockoutjs来绑定选择列表。 Here is a Sample , I want to get selected option text instead of selected value.
这是一个示例 ,我想获取选定的选项文本而不是选定的值。
How to get it using knockoutjs ? 如何使用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>
The simplest way to do it is to remove the optionsValue binding. 最简单的方法是删除optionsValue绑定。 When you don't sepcify the optionsValue binding, the entire item will be the selected value.
当您不sepcify optionsValue绑定时,整个项目将是选定的值。
<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>
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
但您可以轻松创建基于optionValue选择optionText的computedObservable
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);
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.