简体   繁体   中英

How to get the id when selected in the kendo ui autocomplete in knockout js

I am using knock out kendo autocomplete in my application. I want to get the value field of the selected autocomplete. Below is the fiddle for the auto complete. Instead of text I want to display id.

Fiddle

Javascript code:

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>

You can use the select function (and remove the value):

<input data-bind="kendoAutoComplete: { dataTextField: 'name', 
                                       dataValueField:'id', 
                                       data: choices,
                                       select: function(e) { 
    $data.selectedChoice(this.dataItem(e.item.index()).id);
}}" />

Demo

alternate way is by using ko.computed , to get id of selected data.

HTML:

<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());

fiddle: http://jsfiddle.net/novalagung/vp41vc69/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM