Chris Martin
Chris Martin

Reputation: 1889

Knockout select options and dependencies

I have a select list and I want to change the visibility of different divs depending on the selection.

<table>
    <tbody data-bind="foreach: conditions">
        <tr>
            <td>
                <select data-bind="options: $parent.conditionTypes, optionsText: 'name', optionsValue: 'id', value: type"></select>
            </td>
            <td>
                <div data-bind="visible: $parent.isGroupCondition($data)">
                    Group list
                </div>
                <div data-bind="visible: $parent.isTagCondition($data)">
                    Tag list
                </div>
            </td>
            <td>
                <select data-bind="options: $parent.conditionOperations, optionsText: 'name', optionsValue: 'id', value: operation"></select>
            </td>
            <td>
                <input type="text" data-bind="attr: {value: value}" />
            </td>
            <td>
                <a href="#" data-bind="click: $parent.removeCondition.bind($parent)">remove</a>
            </td>
        </tr>
    </tbody>
</table>

I've tried to use the event binding "event: {change: $parent.conditionTypeChanged}" but I'm not sure how to trigger the div's bindings to fire.

Any help is greatly appreciated.

EDIT: JsFiddle

Upvotes: 0

Views: 99

Answers (1)

nemesv
nemesv

Reputation: 139748

You just have to make your type property observable in the items in the conditions

conditions: ko.observableArray([{type: ko.observable(1), operation: 1, value: 'test'}]),

And use the observable in your isGroupCondition and isTagCondition functions:

isGroupCondition: function (condition) {
    return condition.type() === 2;
},
isTagCondition: function (condition) {
    return condition.type() === 1;
},

because your type is now an observable Knockout will take care updating the visibility bindings and hide/show your divs.

Demo JSFiddle.

Upvotes: 1

Related Questions