Search code examples
javascriptknockout.jsknockout-2.0knockout-mapping-pluginknockout-mvc

Two Drop down options binding based on ID knockoutjs


I have the following:

     <select data-bind="options: animals, value: optionsValue: 'ID', optionsText: 'Name'" />

        self.animals = ko.mapping.fromJS([
            {"Name": "Tamed": , "ID": "1" },
            {"Name": "Wild": , "ID": "2" },
            ]);

        self.wildOrTamed = ko.mapping.fromJS([
            { "Name": "Cat", "ID": "1" },
            { "Name": "Lion", "ID": "2" },
            { "Name": "Cat": "1"  },
            { "Name": "Tiger", "ID": "2"  }]);

What I want this to have 2 drop down one for animals to select either Tamed or Wild and then based on that change my wildOrTamed drop down to show either wild animals or Tamed animals using the specified ID.

Note: this is dynamic so there could be other types of animals...

Can anyone help me out with this.

Thanks


Solution

  • Try using computed observable. Check out the fiddle http://jsfiddle.net/aravindbaskaran/6w4N8/

    <select data-bind="options: animalTypes, value: animalType, optionsValue: 'ID', optionsText: 'Name'"></select>
    <select data-bind="options: animalsForType, value: selectedAnimal, optionsValue: 'ID', optionsText: 'Name'"></select>
    
    self.animalTypes = ko.observable([{"Name": "Tamed","ID": "1"},
        {"Name": "Wild","ID": "2"},
        {"Name": "Something else","ID": "3"}]);
    
    self.animals = [{"Name": "Cat","ID": "1"},
        {"Name": "Lion","ID": "2"},
        {"Name": "Cat","ID": "1"}, 
        {"Name": "Tiger","ID": "2"}];
    self.animalType = ko.observable();
    self.selectedAnimal = ko.observable();
    self.animalsForType = ko.computed(function () {
        var selectedType = self.animalType();
        return !selectedType ? [] : self.animals.filter(function (animal) {
            return animal.ID == selectedType;
        });
    });
    

    Hope it helps!