我在我的应用程序中使用敲出剑道自动完成。我想获得所选自动完成的值字段。下面是自动完成的小提琴。我想显示id,而不是文本。
小提琴
Javascript代码:
var ViewModel = function() {
this.choices = ko.observableArray([
{ id: "1", name: "apple"},
{ id: "2", name: "orange"},
{ id: "3", name: "banana"}
]);
this.selectedChoice = ko.observable();
};
ko.applyBindings(new ViewModel());
HTML: <input data-bind="kendoAutoComplete: { dataTextField: 'name',
dataValueField:'id',
data: choices,
value: selectedChoice }" />
Selected: <strong data-bind="text: selectedChoice"> </strong>
您可以使用select
函数(并删除该值):
<input data-bind="kendoAutoComplete: { dataTextField: 'name',
dataValueField:'id',
data: choices,
select: function(e) {
$data.selectedChoice(this.dataItem(e.item.index()).id);
}}" />
演示另一种方法是使用ko.computed
获取所选数据的id。
<input data-bind="kendoAutoComplete: { dataTextField: 'name',
dataValueField: 'id',
data: choices,
value: selectedChoice }" />
Selected: <strong data-bind="text: selectedChoiceId"> </strong>
JS:
var ViewModel = function() {
this.choices = ko.observableArray([
{ id: "1", name: "apple"},
{ id: "2", name: "orange"},
{ id: "3", name: "banana"}
]);
this.selectedChoice = ko.observable('');
this.selectedChoiceId = ko.computed(function () {
var choices = this.choices();
for (var i in choices) {
if (choices[i].name == this.selectedChoice())
return choices[i].id;
}
return "";
}, this);
};
ko.applyBindings(new ViewModel());
小提琴:http://jsfiddle.net/novalagung/vp41vc69/