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><spandata-bind="visible: !IsEditing(), text: Quantity, click: edit"></span><inputdata-bind="value: Quantity, visible: IsEditing, hasfocus: IsEditing" /></td>

Here's a full demo:

functionProductVM(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: [newProductVM({
    Code: function() { return1; },
    Name: function() { return"Apples"; },
    Quantity: function() { return10; },
    Price: function() { return12.50; }
})]})
span { padding: 5px; background: pink; }
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

(Click "10" e.g. the Quantity for demo.)
<table><tbodydata-bind="foreach: OrderedProducts"><tr><td><spandata-bind="text:Code"></span></td><td><spandata-bind="text:Name"></span></td><td><spandata-bind="visible: !IsEditing(), text: Quantity, click: edit"></span><inputdata-bind="value: Quantity, visible: IsEditing, hasfocus: IsEditing" /></td><td><spandata-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"