ryanwaite28
ryanwaite28

Reputation: 2050

Link my search filter to list items : knockout js

I need help linking my ul and li to automatically filter search. i dont know where to go from this.

self.filterMarkers = function() {
  console.log(self.searchQuery);
  var searchInput = self.searchQuery().toLowerCase();

  self.visiblePlaces.removeAll();

  self.allPlaces.forEach(function(place) {
    console.log(place);
    place.marker.setVisible(false);

    if (placeName.toLowerCase().indexOf(searchInput) !== -1) {
      self.visiblePlaces.push(place);
    };
  });

  self.visiblePlaces().forEach(function(place) {
    console.log(place);
    place.marker.setVisible(true);
  });
};

And i need for my list and marker to update when i type in the search input. help?

Upvotes: 1

Views: 1182

Answers (1)

Joel R Michaliszen
Joel R Michaliszen

Reputation: 4222

Maybe if you use the ko.computed(callback,this), i coded a example to show you one of the possibles approachs, i hope be useful X).

See the snnipet.

function ViewModel(){
  var self =this;
  this.filter = ko.observable();
  
  this.places = ko.observableArray([{name:"New York"},{name:"Los Angeles"},{name:"Curitiba"},{name:"Rio de Janeiro"}]);
  
    
  this.visiblePlaces = ko.computed(function(){
       return this.places().filter(function(place){
           if(!self.filter() || place.name.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1)
             return place;
       });
   },this);  
  
    
}

ko.applyBindings(new ViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<label for="filter">Filter:</label>
<input id="filter" type="text" data-bind="textInput: filter"/>

<ul data-bind="foreach: visiblePlaces">
  <li data-bind="text: name"></li>
</ul>

Upvotes: 4

Related Questions