2

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>
Davide Pastore
  • 8,678
  • 10
  • 39
  • 53
SrinivasNaidu
  • 439
  • 2
  • 10
  • 27

2 Answers2

2

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

GôTô
  • 7,974
  • 3
  • 32
  • 43
1

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/

novalagung
  • 10,905
  • 4
  • 58
  • 82