javascript - Knockout filtering items using select selectedIndex matching items by id -
i load second select based on car make. binding selectedindexes ko.observable() variables. know can achieve using optionsvalue : 'id' , binding value observable need use selectedindex in project. thank you
jsfiddle http://jsfiddle.net/diegopitt/xg8q5esu/
my viewmodel:
ko.bindinghandlers.selectedindex = { init: function(element, valueaccessor) { ko.utils.registereventhandler(element, "change", function() { var value = valueaccessor(); if (ko.iswriteableobservable(value)) { value(element.selectedindex); } }); } }; var viewmodel = function(){ var self = this; self.selectedmake = ko.observable(); self.selectedtype = ko.observable(); self.makes = [ {id:1, name: 'dodge'}, {id:2, name: 'bmw'} ]; self.types = [ {id: 1, make:1, name:'neon'}, {id: 2, make:2, name:'328i'} ]; self.cartypes = ko.computed(function(){ return ko.utils.arrayfilter(self.types, function(item){ return item.make === self.selectedmake(); }); }); self.matchingtypes = ko.computed(function () { return ko.utils.arrayfilter(self.cartypes(), function (item, index) { return item.id === self.selectedtype(); }); }); }; var model = new viewmodel(); ko.applybindings(model);
html:
<select id="make" class="form-control select pull-left" data-bind="options: makes, selectedindex: selectedmake, optionstext : 'name'"></select> <select id="type" class="form-control select pull-left" data-bind="options: cartypes, selectedindex: selectedtype, optionstext : 'name'"></select>
since selectedmake set index, self.cartypes
computed needs compare index instead of value:
self.cartypes = ko.computed(function(){ var cartypes = []; if (self.selectedmake() < self.types.length) { cartypes.push(self.types[self.selectedmake()]) } return cartypes; });
Comments
Post a Comment