使用KnockoutJS从多个选择列表中获取值

时间:2019-06-20 16:56:04

标签: knockout.js

html

<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..'"></select>
<br/>
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..'"></select>
<input type="button" data-bind="click: sendMe, enable: selectedChoice" Value="Click Me"/>

KnockoutJS

var CountryModel = function(data){
    var self = this;

    self.id = ko.observable(data.id);
    self.name = ko.observable(data.name);
};
var viewModel = function(data) {
   var self = this
   self.selectedChoice = ko.observable();

   self.countries = ko.observableArray([
        new CountryModel({id: "1", name: "Russia"}),
        new CountryModel({id: "2", name: "Qatar"})]);
    self.sendMe = function(){


        alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
    };

};

ko.applyBindings(new viewModel());

我有两个问题:

  1. 如何使选择列表独立?
  2. 如何从每个值中获取选定的值?

1 个答案:

答案 0 :(得分:0)

在视图模型中只需要2个独立的可观察对象即可存储每个列表的选定值;
这里selectedChoice1selectedChoice2

请参见下面的可运行示例。

var CountryModel = function(data){
    var self = this;

    self.id = ko.observable(data.id);
    self.name = ko.observable(data.name);
};

var viewModel = function(data) {
   var self = this
   self.selectedChoice1 = ko.observable();
   self.selectedChoice2 = ko.observable();

   self.countries = ko.observableArray([
        new CountryModel({id: "1", name: "Russia"}),
        new CountryModel({id: "2", name: "Qatar"})]
        );
   self.sendMe = function(){    
        alert(ko.toJSON({ 
            "selectedCountryId1": this.selectedChoice1(), 
            "selectedCountryId2": this.selectedChoice2() 
            }));
    };
};

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice1, optionsCaption: 'Choose..'"></select>
<br/>
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice2, optionsCaption: 'Choose..'"></select>
<input type="button" data-bind="click: sendMe, enable: (selectedChoice1() && selectedChoice2())" Value="Click Me"/>