Skip to content Skip to sidebar Skip to footer

How To Create Linked Dropdowns Sharing A Single List And Ensure Each Value Can Only Be Selected In One Dropdown?

I am trying to create a group of dropdowns using knockout out that allow users to select up to 3 values from a list e.g. colours. The list starts as:- Red,orange,yellow,green,blue

Solution 1:

This is definitely possible in Knockout. And there's probably 10 ways to do it. I've come up with one way here:

http://jsfiddle.net/mbest/wfW97/

Here's the code for reference:

functionViewModel() {
    varself = this;
    self.colors = ['red','orange','yellow','green','blue','indigo','violet'];
    self.selections = [];
    ko.utils.arrayForEach(self.colors, function() {
        self.selections.push(ko.observable());
    });
    self.selfAndUnselectedColors = function(index) {
        var selfColor = self.selections[index]();
        return ko.utils.arrayFilter(self.colors, function(color) {
            return color === selfColor || !ko.utils.arrayFirst(self.selections, function(sel) {
                return color === sel();
            });
        });
    }
}
ko.applyBindings(new ViewModel());

And HTML:

<div data-bind="repeat: colors.length">
    <select data-bind="options: selfAndUnselectedColors($index), optionsCaption: 'select a color', value: selections[$index]"></select>
</div>​

I'm using my repeat binding plugin to create the repeated select elements, but you could use some other method if you wanted.

Post a Comment for "How To Create Linked Dropdowns Sharing A Single List And Ensure Each Value Can Only Be Selected In One Dropdown?"