Logan H
Logan H

Reputation: 3423

Delete Table Row from nested <ul> list item

I have a html table that has an <ul> in it. The table is bound by a knockout view model.

When I click on the TEST text I would like remove the <tr> that the clicked TEST text is in, from the table. I have it now so when I click on REMOVE it removes the <tr> but I need it so when I click on the TEST it removes the <tr>. Help is greatly appreciated!

FIDDLE with it, and/or see code snippet below.

VIEW MODEL

var rowModel = function(id, list) {
  this.uid = ko.observable(id);
  this.myList = ko.observableArray(list);
};

function myViewModel() {
  var self = this;
  self.myArr = ko.observableArray([
    new rowModel(1, ["str1", "str2", "str3"]),
    new rowModel(2, ["str1", "str2"]),
    new rowModel(3, ["str1"])
  ]);

  //this.myList = ko.observableArray();

  self.removeItem = function(rowItem) {
    self.myArr.remove(rowItem);

  }
}

ko.applyBindings(new myViewModel());
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table class="table table-striped">
  <thead>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
  </thead>
  <tbody data-bind="foreach: myArr">
    <tr>
      <td data-bind="text: uid"></td>
      <td>
        <ul data-bind="foreach: myList">
          <li><span data-bind="text: $data"></span>  <a href="#" data-bind="click: $parents[1].removeItem">TEST</a>
          </li>
        </ul>
      </td>
      <td><a href="#" data-bind="click: $root.removeItem">REMOVE</a>
      </td>
    </tr>
  </tbody>
</table>

Upvotes: 0

Views: 128

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134811

The problem is that the context of the data for the TEST link is a myList item, not a myArr item. Your removeItem() function is expecting a myList item. You need to pass the data from the (in this case) parent context. You can use $parentContext.$data or simply $parent.

<ul data-bind="foreach: myList">
    <li>
        <span data-bind="text: $data"></span>
        <a href="#" data-bind="click: function () { $root.removeItem($parent); }">TEST</a>
    </li>
</ul>

Upvotes: 1

Related Questions