Dependable select option using knockout

by Keyur Patel

HTML

<div>
    <select id="make" data-bind="options: carMakers, value: selectedMake, optionsText : 'text', optionsCaption : 'Select your make'"></select><br/>
    <select id="type" data-bind="options: carTypes, value: selectedType, optionsText : 'text', optionsCaption : 'Select your type', enable : carTypes"></select><br/>
    <select id="model" data-bind="options: carModels, value: selectedModel, optionsText : 'text', optionsCaption : 'Select your Model', enable: carModels"></select>
</div>

CSS

select
{
    width:150px;
}

JavaScript

//Define our options model
var cascadingOption = function(data){
    var self = this;
    self.text = data.text;
    self.childOptions = data.childOptions;
}

//fill our models with example data
function buildData(){
    var fordTrucks = new cascadingOption({
        text: 'Trucks',
        childOptions : [
            new cascadingOption({
                text: 'F150'
            }),
            new cascadingOption({
                text: 'SuperDuty'
            })
        ]
    });

    var fordCars = new cascadingOption({
        text: 'Cars',
        childOptions : [
            new cascadingOption({
                text: 'Focus'
            }),
            new cascadingOption({
                text: 'Mustang'
            })
        ]
    });

    var fords = new cascadingOption({
        text: 'Ford',
        childOptions : [fordTrucks, fordCars]
    });

    var audis = new cascadingOption({
        text: 'Audi',
        childOptions : [
            new cascadingOption({
                text:'Crossovers',
                childOptions : [
                    {text: 'Q5'},
                    {text: 'Q7'}
                ]
            }),
            new cascadingOption({
                text:'Cars',
                childOptions : [
                    {text: 'A3'},
                    {text: 'A4'},
                    {text: 'A6'}
                ]
            })
        ]
    });

    return [fords, audis];
}

var viewModel = {
    carMakers: buildData(),
    selectedMake : ko.observable(),
    selectedType : ko.observable(),
    selectedModel : ko.observable()
};

viewModel.carTypes = ko.computed(function(){
    return viewModel.selectedMake() ? viewModel.selectedMake().childOptions : null;
});

viewModel.carModels = ko.computed(function(){
    return viewModel.selectedType() ? viewModel.selectedType().childOptions : null;
});


ko.applyBindings(viewModel);