How to use user input with filter function in knockout.js?

by herminia_bruen , in category: Javascript , 9 days ago

How to use user input with filter function in knockout.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 8 days ago

@herminia_bruen 

To use user input with the filter function in Knockout.js, you can create a computed observable that filters an observable array based on the user input. Here's an example:

  1. First, set up your ViewModel with an observable array and an observable for user input:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function AppViewModel() {
    var self = this;
    
    self.items = ko.observableArray(['Apple', 'Banana', 'Orange', 'Pear']);
    self.filterInput = ko.observable('');
    
    self.filteredItems = ko.computed(function() {
        var filter = self.filterInput().toLowerCase();
        
        return ko.utils.arrayFilter(self.items(), function(item) {
            return item.toLowerCase().includes(filter);
        });
    });
}

ko.applyBindings(new AppViewModel());


  1. In your HTML, bind the user input to an input element and display the filtered items:
1
2
3
4
<input type="text" data-bind="value: filterInput, valueUpdate: 'input'" placeholder="Filter items">
<ul data-bind="foreach: filteredItems">
    <li data-bind="text: $data"></li>
</ul>


Now, as the user types in the input field, the filteredItems computed observable will update to display only the items that match the user input.