javascript - Load selected values in dropdown on selecting value from another dropdown -
i have 2 dropdowns. when select value 1 dropdown load values in dropdown depending upon selected.
here html code
<select data-bind="options: filters, value: filter"></select> <select data-bind="options: filtereditems, optionstext: 'name'"></select>
here 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 select type none selects cars , if select type other none should select "charger" , "magnum"
here link fiddle
first of all, if want return items, return self.items()
, slice not needed. if want return items matching filter, 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 working fiddle.
if want select "charger" , "magnum" here 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] ]; } });