Skip to content Skip to sidebar Skip to footer

Show/hide Elements Dynamically Using Knockout

I have a table which has four columns namely Code, Name, Quantity and Price. Out of these, I want to change the content/element of Quantity column dynamically. Normally, it should

Solution 1:

The problem is tricky. It lies in the fact that span is not a self-closing element. This will work:

<td>
    <span data-bind="visible: !IsEditing(), text: Quantity, click: edit"></span>
    <input data-bind="value: Quantity, visible: IsEditing, hasfocus: IsEditing" />
</td>

Here's a full demo:

function ProductVM(vm) {
    var self = this;

    self.Code = ko.observable(vm.Code());
    self.Name = ko.observable(vm.Name());
    self.Quantity = ko.observable(vm.Quantity());
    self.Price = ko.observable(vm.Price());
    self.IsEditing = ko.observable(false);

    this.edit = function () {
        self.IsEditing(true);
    }
}

ko.applyBindings({ OrderedProducts: [new ProductVM({
    Code: function() { return 1; },
    Name: function() { return "Apples"; },
    Quantity: function() { return 10; },
    Price: function() { return 12.50; }
})]})
span { padding: 5px; background: pink; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

(Click "10" e.g. the Quantity for demo.)
<table>
  <tbody data-bind="foreach: OrderedProducts">
    <tr>
      <td><span data-bind="text:Code"></span></td>
      <td><span data-bind="text:Name"></span></td>
      <td>
        <span data-bind="visible: !IsEditing(), text: Quantity, click: edit"></span>
        <input data-bind="value: Quantity, visible: IsEditing, hasfocus: IsEditing" />
      </td>
      <td><span data-bind="text:Price"></span></td>
    </tr>
  </tbody>
</table>

Remember, the same holds for div elements, don't use them in a self-closing manner or Knockout will fool you when you least expect it.


Post a Comment for "Show/hide Elements Dynamically Using Knockout"