如何使用knockout从下拉列表中获取选定的值

时间:2016-05-03 13:47:57

标签: javascript jquery knockout.js knockout-2.0

所以我正在使用knockout并试图在我的javascript中获取所选项目的id更改事件。这是我的HTML

 <div id="platforms" data-bind="with: platformsViewModel">
            <p>
                Selected Platform:
                <select data-bind="options: platforms, optionsText: 'displayName', value: 'id', optionsCaption: 'Choose...', event: { change: loadMedias }" ></select>
            </p>
        </div>

我的视图模型如下

my.viewModels.PlatformsViewModel = function () {
    var self = this;

    self.platforms = ko.observableArray();
    self.message = ko.observable();

    self.loadMedias = function (data, event) {
        my.loadMedias(data.id);
    }
}

我在这里缺少什么?

2 个答案:

答案 0 :(得分:4)

看起来这样可能是一个简单的修复,你可能会使用value绑定,你应该使用optionsValue绑定:

<select data-bind="options: platforms, optionsText: 'displayName', optionsValue: 'id', optionsCaption: 'Choose...', event: { change: loadMedias }" ></select>
                                                              <!-- ^ here -->

但是,为什么不将逻辑放在视图模型中,而不是放在视图中:

my.viewModels.PlatformsViewModel = function () {
    var self = this;

    self.platforms = ko.observableArray();
    self.message = ko.observable();

    //new observable to hold selected platform
    self.selectedPlatform = ko.observable();
    //subscribe to changes in the observable value to trigger the loading
    self.selectedPlatform.subscribe(function(newValue) {
        my.loadMedias(newValue.id);
    });
}

更新的<select>将绑定所选的实际平台对象,而不仅仅是其ID:

<select data-bind="options: platforms, optionsText: 'displayName', value: selectedPlatform, optionsCaption: 'Choose...'" ></select>

答案 1 :(得分:-1)

HTML:

<select name="ddlUsers" id="ddlUsers" class="form-control"
                            data-bind="options: ViewModel.CashierPage.AvailableCash,  optionsText: 'OptionTextInfo', value: ViewModel.CashierPage.CashSelected, optionsCaption: 'Cassa...'"></select>

在js:

 public CashSelected: KnockoutObservable();
...
 self.CashSelected = ko.observable(null);
 self.CashSelected.subscribe(function(valueNewValue){/*your code*/});