Reputation: 23
I'm new to KnockoutJS and having trouble getting the text and input "Other Reason" to only be visible when in the dropdown "Other" is selected. Please help.
<div id="reasonPopup" class="selectItems" style="display: none; position: absolute; width: 200px; height: 150px;">
Choose an Reason:<br />
<select data-bind="options: reasons,
optionsText: 'reasonText',
optionsValue: 'reasonValue',
value: chosenReason,
optionsCaption: 'Choose...'"></select>
<p data-bind="with: chosenReason">
Other Reason: <input data-bind="value: $root.chosenReason, visible: chosenReason == 'Other'" />
</p>
<p data-bind="with: chosenReason">
You have chosen <b data-bind="text: $root.chosenReason"></b>
</p>
<br />
<input type="button" data-bind="click: setReason('OK'), enable: chosenReason" value="OK" />
<input type="button" data-bind="click: setReason('Cancel'), disable: chosenReason" value="Cancel" />
<br />
Upvotes: 2
Views: 2066
Reputation: 14995
Here is a pseudo-working example of what you are trying to do -
<p data-bind="if: chosenReasonId() === 'Other'">
Other Reason: <span data-bind="text: chosenReasonId"></span>
</p>
<p data-bind="ifnot: chosenReasonId() === 'Other'">
You have chosen <b data-bind="text: chosenReasonId"></b>
</p>
Basically you need to use the if binding to compare what you want to show based on criteria.
Upvotes: 0
Reputation: 79461
Use visible: chosenReason() === 'Other'
in your binding (emphasis on the added parentheses). You are currently comparing the observable to 'Other'
when you intend to compare the current value of the observable.
Another way to do this would be to include another observable in your view model, then bind to that:
self.isOtherReason = ko.computed(function () {
return self.chosenReason() === 'Other';
});
It would also make sense to perform your visible
binding on the <p>
containing the <input>
, rather than on the <input>
directly.
Upvotes: 3