Reputation: 35
I have a project in which I have to create a live search using Knockout. I found a tutorial on how to do it but when I implement it in my code it does not work. The search should be done on an array and display the items from the array that matches the term input by the user. the final product should look like this image
https://github.com/silvodesigns/Neighborhood-Map tutorial--opensoul.org/2011/06/23/live-search-with-knockoutjs/
Upvotes: 1
Views: 866
Reputation: 4222
You can use ko.computed
and textInput
binding to always notify the changes and apply filters.
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: 2