Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
})
like image 236
BrianMichaels Avatar asked Feb 06 '13 19:02

BrianMichaels


2 Answers

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'"  />
like image 139
Konstantin Dinev Avatar answered Oct 01 '22 15:10

Konstantin Dinev


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.

like image 21
Ben McCormick Avatar answered Oct 01 '22 15:10

Ben McCormick