Popmatik
Popmatik

Reputation: 107

Knockout.js cascading options with JSON

I've been trying to make a cascading drop down list that is populated by JSON. I have found that when I change the gender value from Male to Female on the front end by using the select drop down. The Female option is the only one that remains in the drop down after this point. I think what I am doing by decalaring the value: gender is overwritting the gender variable?

Any help would be greatly appreciated. I'm new to Knockout so I'm hoping what I want to achieve is possible.

Thanks in advance.

Here is the code I have created:

HTML:

<select data-bind="options: gender, optionsText: 'name', value: gender"></select><br />
<select data-bind="options: gender().garments, optionsText: 'garmentName'"></select>

JS:

function streckViewModel(){ 

};

$.getJSON("js/garments.json", null, function(garmentData, status, xhr){
streckViewModel = ko.mapping.fromJS(garmentData);
ko.applyBindings(streckViewModel);
});

JSON:

{
"gender":[

    {

        "name" : "male",

            "garments": [
                { "garmentName": "hoodie" },
                { "garmentName": "t-shirt" }
            ]

    },

    {
        "name" : "female",

            "garments": [
                { "garmentName": "hoodie" },
                { "garmentName": "blouse" }
            ]
    }

]

}

Upvotes: 1

Views: 112

Answers (1)

Simon Bull
Simon Bull

Reputation: 881

Try changing your HTML to something like:

<select data-bind="options: gender, optionsText: 'name', value: selectedGender"></select><br />
<select data-bind="options: selectedGender.garments, optionsText: 'garmentName'"></select>

Upvotes: 1

Related Questions