Tom Rudge Tom Rudge - 27 days ago 5
HTML Question

KO IF observable matches value show/hide

<input type="text" data-bind="value: myObs" />
var myObs = ko.observable();
<!-- ko if: myObs === "hello" -->
Whatever! html etc...
<!-- /ko -->


If my observable value equals "hello" then show "whatever!". When a user inputs "hello" I want this field to show and when it gets removed from input it disappears again.

Answer

You need to add brackets after myObs, otherwise you're comparing the observable function to the "hello" string and not the value of the observable itself:

var vm = {
  myObs: ko.observable("hello")
}

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="value: myObs, valueUpdate: 'input'" />
<!-- ko if: myObs() === "hello" -->
  Whatever! html etc...
<!-- /ko -->

Comments