2

アプリケーションでノックアウト剣道オートコンプリートを使用しています。選択したオートコンプリートの値フィールドを取得したい。以下は、オートコンプリートのフィドルです。テキストの代わりに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>
4

2 に答える 2

1

別の方法は、を使用してko.computed、選択したデータの ID を取得することです。

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

フィドル: http://jsfiddle.net/novalagung/vp41vc69/

于 2015-12-14T04:04:49.647 に答える