Mohammed Mohammed
Mohammed Mohammed

Reputation: 43

knockout array filter based on list of checkbox selected

I am struggling to filter list in the body based on the selection of list of checkboxes under the protocol in the left see on jsfiddle please help.

filteredRecords: function(){
        return ko.utils.arrayFilter(viewModel.protocoldocs,function(protocoldoc){
           var flag = false;
    foreach(selprotocol in viewModel.selectedprotocol)
    {

        if(selprotocol.id === protocoldoc.pronumber)
        flag = true;     
    }
    return flag;
        })};

Upvotes: 2

Views: 973

Answers (1)

Sam.C
Sam.C

Reputation: 1621

You could use a computed observable for this purpose like below

viewModel.filteredProtocols = ko.computed(function () {
  var selectedProtocols = ko.utils.arrayFilter(viewModel.protocol(), function (p) {
    return p.selected();
  });
  if (selectedProtocols.length == 0)   //if none selected return all
    return viewModel.protocoldocs();
  else { //other wise only return selected protocoldocs
    return ko.utils.arrayFilter(viewModel.protocoldocs(), function (item) {
      return ko.utils.arrayFilter(selectedProtocols, function (p) {
        return p.id == item.id
      }).length > 0;
    });
  }
})

and bind your result table to this filteredProtocol. A couple of things that i have also modified are

I added a selected flag for protocol to retain checked values

<input type="checkbox" data-bind="checked:selected, attr: {id: 'checkBox' + id}">

...

function protocol(id, name) {
  this.id = id;
  this.name = name;
  this.selected = ko.observable(false);
}

you can find a working sample here http://jsfiddle.net/prc4pqnm/3/

Upvotes: 4

Related Questions