knockout.js - Knockout data binding a textarea within foreach -


within foreach, have span tag , textarea. whenever click span tag, want toggle visibility of textarea.

this works partially except toggles visibility of all of textareas within foreach instead of textarea particular item on.

here code. code doesn't run, think there's enough there see trying do.

function myviewmodel(data) {   var self = this;   self.checklistitems = [1,2,3];   self.textareavisible = ko.observable(false);      self.toggletextarea = function () {          self.textareavisible(!self.textareavisible());   }  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>  <div data-bind="foreach: myviewmodel.checklistitems">           <span data-bind="click: toggletextarea">add comments ></span>           <textarea data-bind="value: comments, visible: textareavisible"></textarea>  </div>

i found link here http://knockoutjs.com/documentation/foreach-binding.html sounds maybe should using $data somehow, i'm not sure how work in context.

i appreciate can provide.

your checklist items should more (i.e. objects):

self.checklistitems = [     { value: 1, visible: ko.observable(false) },     { value: 2, visible: ko.observable(false) },     { value: 3, visible: ko.observable(false) }, ]; 

doing enables iterate this:

<div data-bind="foreach: myviewmodel.checklistitems">          <span data-bind="click: function(){ visible(!visible()) }">add comments ></span>          <textarea data-bind="value: value, visible: visible"></textarea> </div> 

should want cleanup click handler, can modify viewmodel follows:

function myviewmodel(data) {  //rest of code   self.toggletextarea = function (item) {     item.visible(!item.visible());  } } 

changing dom this:

 <div data-bind="foreach: myviewmodel.checklistitems">              <span data-bind="click: $parent.toggletextarea">add comments ></span>              <textarea data-bind="value: value, visible: visible"></textarea>     </div> 

Comments