NoviceDeveloper
NoviceDeveloper

Reputation: 1290

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

Upvotes: 0

Views: 608

Answers (2)

aravind
aravind

Reputation: 2877

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!

Upvotes: 3

Jalpesh Vadgama
Jalpesh Vadgama

Reputation: 14266

Hi I'm not 100% sure but following link will help you creating cascading drop down. http://www.dotnetexpertguide.com/2012/06/cascading-dropdown-knockoutjs-aspnet.html

Upvotes: 0

Related Questions