简体   繁体   中英

Load selected values in dropdown on selecting value from another dropdown

I have 2 dropdowns. When i select value from one dropdown it will load values in another dropdown depending upon what is selected.

Here is my html code

<select data-bind="options: filters, value: filter"></select>

<select data-bind="options: filteredItems, optionsText: 'name'"></select>

Here is my knockout code

var ViewModel = function(data) {
var self = this;
self.filters = ko.observableArray(data.filters);
self.filter = ko.observable('');
self.items = ko.observableArray(data.items);
self.filteredItems = ko.computed(function() {
    var filter = self.filter();
    if (!filter || filter == "None") {
        return self.items.slice(0, 6);
    } else {
        return self.items.slice(2);
    }
  });
};


  var initialData = {
     filters: ["None", "Old", "New", "Super"],
       items: [{ name: "Corvette", type: "Old"},
       { name: "Charger", type: "Old"},
       { name: "Prius", type: "New"},
       { name: "Magnum", type: "New"},
       { name: "McLaren", type: "Super"},
       { name: "Saleen", type: "Super"}]


   ko.applyBindings(new ViewModel(initialData));

When i select Type as None then it selects all Cars and if i select type other than None then it should only select "Charger" and "Magnum"

Here is the link to fiddle

First of all, if you want to return all items, just return self.items() , the slice is not needed. If you want to return items matching the filter, this should work:

self.filteredItems = ko.computed(function() {
    var myFilter = self.filter();
    if (!myFilter || myFilter == "None") {
        return self.items();
    } else {
        var tempArray = [];
        for(i=0; i<self.items().length; i++) {
            if(self.items()[i].type == myFilter) {
                tempArray.push(self.items()[i]);
            }
        }
        return tempArray;
    }
});

Check the working fiddle .


If you want to select only "Charger" and "Magnum" here it goes:

self.filteredItems = ko.computed(function() {
    var myFilter = self.filter();
    if (!myFilter || myFilter == "None") {
        return self.items();
    } else {
        return [ self.items()[1], self.items()[3] ];
    }
});

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