javascripthtmlknockout.js

KnockoutJS show/hide div based on string


I have a model knockoutJS model having the following structure:

this.optionGroup = ko.obervable({});

And there is an option in this object called isAvailable and its value is either "true" or "false".

The problem I am having is to show Yes in case of "true" and No in case of "false" so that it would be more friendly to the user. I have tried various options, with the last one being the following:

<div data-bind="text: optionGroup().isAvailable === 'true'? 'Yes' : 'No'"></div>

Unfortunately this is always evaluating to false, and thus showing 'No' in the HTML. This is my first time using knockoutJS as this is a legacy page, and not sure if there's a way to easily show Yes/No label based on the value set in isAvailable.

Thanks


Solution

  • From your comment:

    I am setting the value like this: object.isAvailable = "true" model.optionGroup(ko.mapping.fromJS(object)); (object is the response of an ajax call, and above I am hardcoding the value).

    That means isAvailable is an observable, since that's the job of the mapping plugin. So my #3 from my comment applies, you want:

    <div data-bind="text: ko.unwrap(optionGroup().isAvailable) === 'true'? 'Yes' : 'No'"></div>
    

    Or if you're always going to make sure you've made that mapper call before the view renders, you can use () instead of ko.unwrap:

    <div data-bind="text: optionGroup().isAvailable() === 'true'? 'Yes' : 'No'"></div>
    

    My first version uses ko.unwrap because in your initial optionGroup object, there's no isAvilable at all, so if we just used .isAvailable(), it would throw, whereas ko.unwrap(...) won't.


    Or as I said in a separate comment, a computed instead:

    this.optionGroup = ko.obervable({});
    this.optionGroupAvailableText = ko.pureComputed(function() {
        return ko.unwrap(this.optionGroup().isAvailable) === 'true'? 'Yes' : 'No';
    }, this);
    

    then:

    <div data-bind="text: optionGroupAvailableText"></div>