knockout js if statement to Display value based on boolean data type

14,901

Solution 1

In this kind of case you can evaluate the property and render based on the value. Even a function can be provided inside the binding. You can use this:

<input type="text"  data-bind="value: Support() ? 'Supported' : 'Not Supported'"  />

Solution 2

What you're looking for, in this case, is ko.computed().

EDITED: (Support appears to be in-use as a value from the data set) Add a new value to your ViewModel, something like this:

IsSupported = ko.computed(function(){
    if(this.Support() == true){
        return "Supported";
    } else {
        return "Not Supported";
    }
}, this)

Then, in your markup, you will have to change your data-bind just slightly:

<p><input type="text" data-bind="value: IsSupported" /></p>

Alternatively, if you don't want to change your Support field, you'll have to do something like this in your HTML, as suggested by other commenters:

<p><input type="text"  data-bind="value: (Support() ? 'Supported' : 'Not Supported')"  /></p>

I'd recommend the former, however, as really, you should keep that logic tucked away inside your ViewModel.

(See the KO docs for more info on computed: http://knockoutjs.com/documentation/computedObservables.html)

Solution 3

You can do that with the if binding

See documentation here

Example from the docs:

<label><input type="checkbox" data-bind="checked: displayMessage" /> Display message</label>

<div data-bind="if: displayMessage">Here is a message. Astonishing.</div>

So for you

<div data-bind="if: Support">Supported</div>
<div data-bind="ifnot: Support">Not Supported</div>

Edit: The other answers suggesting using the value binding with a ternary condition are probably a better way to accomplish this. I'll keep this up as a reference, but I recommend that solution.

Share:
14,901
BrianMichaels
Author by

BrianMichaels

Updated on June 12, 2022

Comments

  • BrianMichaels
    BrianMichaels almost 2 years

    I am trying to Display a value based on a table value of True or False. For example if the Value is True then I want it to Say Supported and If it's False then I want it to Say Not Supported! This is my html code

    <p><input type="text"  data-bind="value: Support"  /></p>
    

    Java script Code

    $(function() {
      dm.viewModel = function() {
        var clients = ko.observableArray(),
          selectedClient = ko.observable(),
    
          clientChanged = function() {
            $.getJSON(dm.WebServices + "/dm/get/clientinfo?client=" + encodeURIComponent(selectedClient()), function(data) {
              if (data != null) {
                dm.viewModel.Name(selectedClient());
                dm.viewModel.Support(data[0]['Support']);
              }
            })
            $('#divClientData').show();
          },
    
          LoadClients = function() {
            $('#divClientData').hide();
            $.getJSON(dm.WebServices + "/dm/get/clientlist", function(data) {
              $.each(data, function(key, val) {
                clients.push(val);
              });
            });
          },
    
          Name = ko.observable(),
          Support = ko.observable(),
    
          return {
            Name: Name,
            Support: Support
          };
      }();
    
      ko.applyBindings(dm.viewModel);
      dm.viewModel.LoadClients();
    })
    
  • Ben McCormick
    Ben McCormick over 11 years
    Your second solution will not work, the Support variable would need () afterwards to properly be computed. Regardless, the if binding is much more straightforward, as it was created for this purpose.
  • Jason M. Batchelor
    Jason M. Batchelor over 11 years
    Thanks for the amendment in regard to Support(). I prefer to take the approach that extra markup is wasted markup (and not very DRY), personally, but whichever gets you where you need to go.
  • BrianMichaels
    BrianMichaels over 11 years
    I used the ko.computed and I get this error -- Uncaught Error: Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.
  • Jason M. Batchelor
    Jason M. Batchelor over 11 years
    So, Support maps to an actual value in your data. In that case, you need to follow the second example (with the data-bind modification in the markup, leaving Support as a ko.observable() in your ViewModel). I've edited my answer to accommodate this.
  • Jason M. Batchelor
    Jason M. Batchelor over 11 years
    (And yes, I'm aware that my example could use a ternary operator in the computed function for more brevity. I did it that way more for clarity.)
  • abarisone
    abarisone about 9 years
    Could you please elaborate more your answer adding a little more description about the solution you provide?
  • Matansh
    Matansh about 9 years
    Basically, I'm enabling the visibility of the div "bla" only if the position (KO parameter) is different than value (which can also be a KO parameter). The visibility gets true if position is different than the value, and false if they are different