I try to search by name in observable array. Here's my code:
<input class="form-control" data-bind="value: Query, valueUpdate: 'keyup'" autocomplete="off">
And my code in ViewModel
viewModel.Query = ko.observable('');
viewModel.search = function(value) {
viewModel.TestList.removeAll();
for (var x in viewModel.TestList) {
if (viewModel.TestList[x].Name.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
viewModel.TestList.push(viewModel.TestList[x]);
}
}
}
viewModel.Query.subscribe(viewModel.search);
First: I would like to search by name string. Two: Is there any other sollutions to not remove all elements from the view? I mean when query string is empty, there should be all list again.
Now I have error message:
TypeError: viewModel.TestList[x].Name is undefined
Use a computed observable array to show search results, along these lines:
var viewModel = {
items: [ { Name: "Apple part" }, { Name: "Apple sauce" }, { Name: "Apple juice" }, { Name: "Pear juice" }, { Name: "Pear mush" }, { Name: "Something different" } ]
};
viewModel.Query = ko.observable('');
viewModel.searchResults = ko.computed(function() {
var q = viewModel.Query();
return viewModel.items.filter(function(i) {
return i.Name.toLowerCase().indexOf(q) >= 0;
});
});
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input class="form-control" data-bind="value: Query, valueUpdate: 'keyup'" autocomplete="off">
<h3>Search results:</h3>
<ul data-bind="foreach: searchResults">
<li data-bind="text: Name"></li>
</ul>
<h3>All items:</h3>
<ul data-bind="foreach: items">
<li data-bind="text: Name"></li>
</ul>
This also removes the need for a subscription or seperate function.
This example utilizes:
observableArray
for storing all items
(this list is always the same, regardless of your search query);filter
method (you call it on the observableArray
, but KO just forwards it to the underlying array);As you can see in the example, items
will always contain all objects, and searchResults
is just a filtered read-only view on that array.