Question

I need to present 5 dropdown lists in my UI, populated with a Knockout ObservableArray. All 5 read from the same source ko.observableArray([]).

I have two problems:

  1. How do I make each option only become active after the option before it has been selected? Should only have the first dropdown active, once a selection has been made then activate teh second one, until user has selected all 5.

  2. Each dropdown is reading from the same observableArray, but I don't want users to be able to select the same option as prior the dropdowns. How do I make the second dropdown show all options excluding what as picked in the first dropdown? How do I make the third dropdown show all optoins excluding what was selected in the first and second dropdown? I can do cascading dropdowns from loading from different sources, but I don't really want to have to make 5 separate $.getJSON calls, I'd much prefer one at the initial pageLoad.

I've found a few prior questions on cascading select lists, but not for reading from the same one source...

Was it helpful?

Solution

You can use the enable binding to connect the previous select value with the second select.

So when you select something in the first dropwdown the firstValue will contain the selected value so the enable: firstValue will be true and it will enable the second dropdown

<select data-bind="options: options, optionsText: 'value', 
                   optionsCaption: '', value: firstValue"></select>
<select data-bind="options: secondOptions, optionsText: 'value', 
                   optionsCaption: '',value: secondValue, 
                   enable: firstValue"></select>

To solve the "cascading" you can use computed properties to fill in the options with filtering out the already selected values:

var VM = function () {

    this.options = ko.observableArray(/* load your original options here */);

    this.firstValue = ko.observable();
    this.secondValue = ko.observable();

    this.secondOptions = ko.computed(function () {
        return ko.utils.arrayFilter(this.options(), function (item) {
            return item != firstValue();
        });
    }, this);
}

And apply these patterns for the other 3 dropdowns.

Demo JSFiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top