简体   繁体   中英

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" }
            ]
    }

]

}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM