In Knockout.js, filters are commonly used to manipulate and format data before displaying it in the UI. Filters allow you to apply transformations to observable data without modifying the underlying data itself. Here's how you can use filters in Knockout.js:
1. Define a Custom Filter Function
First, define a custom filter function that takes input data and returns the transformed output. You can define this function anywhere in your code, typically within your view model or a separate utility module.
// Custom filter function
function capitalize(value) {
if (!value) return '';
return value.charAt(0).toUpperCase() + value.slice(1);
}
2. Use the extenders Binding Handler
Next, use the extenders binding handler provided by Knockout.js to apply the filter to an observable. The
extenders binding handler allows you to extend the behavior of an observable by applying one or more "extensions" or filters.
// Extender to apply the filter
ko.extenders.capitalize = function(target) {
target.capitalized = ko.computed(function() {
return capitalize(target());
});
return target;
};
3. Apply the Filter to Observables
Now, apply the custom filter to your observables when defining them in your view model. You can use the
extend function provided by Knockout.js to apply the filter.
// ViewModel
function AppViewModel() {
this.firstName = ko.observable('').extend({ capitalize: true });
this.lastName = ko.observable('').extend({ capitalize: true });
var self = this;
// Observable array containing the original data
self.items = ko.observableArray([
'Carrot', 'Apple', 'Banana', 'Orange', 'Broccoli'
]);
// Observable to store the filter criteria
self.filter = ko.observable('');
// Computed observable to filter the items based on the filter criteria
self.filteredItems = ko.computed(function () {
var filter = self.filter().toLowerCase(); // Convert filter criteria to lowercase
if (!filter) {
return self.items(); // If no filter, return all items
} else {
// Filter the items based on the filter criteria
return ko.utils.arrayFilter(self.items(), function (item) {
return item.toLowerCase().indexOf(filter) !== -1; // Case-insensitive match
});
}
});
// Computed observable to get the length of the filtered items
self.filteredItemsLength = ko.computed(function () {
return self.filteredItems().length; // Return the length of the filtered items array
});
}
4. Bind to the Filtered Data in the UI
Finally, bind to the filtered data in your HTML using the computed property created by the filter. This property will automatically update whenever the original observable changes.
<!doctype html>
<html lang="en">
<head>
<!-- Meta tags for character set and viewport configuration -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Title of the webpage -->
<title>Bootstrap demo</title>
<!-- Link to Bootstrap CSS for styling -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<!-- Link to Knockout.js library for MVVM pattern support -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.min.js"
integrity="sha512-vs7+jbztHoMto5Yd/yinM4/y2DOkPLt0fATcN+j+G4ANY2z4faIzZIOMkpBmWdcxt+596FemCh9M18NUJTZwvw=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<div class="container">
<h1>Knockout.js Filters Demo</h1>
<div>
<label for="firstNameInput">First Name:</label>
<input type="text" id="firstNameInput" data-bind="value: firstName">
<p>Capitalized First Name: <span data-bind="text: firstName.capitalized"></span></p>
</div>
<div>
<label for="lastNameInput">Last Name:</label>
<input type="text" id="lastNameInput" data-bind="value: lastName">
<p>Capitalized Last Name: <span data-bind="text: lastName.capitalized"></span></p>
</div>
<hr />
<div class="">
<!-- Page heading -->
<h1>Filtering Observable Array</h1>
<div>
<!-- Input field for filtering items in the observable array -->
<input class="form-control" autofocus="true" type="text" placeholder="Enter search keyword"
data-bind="value: filter, valueUpdate: 'keyup'">
<!-- Display the number of filtered items found, if any -->
<p class="fw-bold pt-2" data-bind="if: filteredItemsLength">
<span data-bind="text: filteredItemsLength"></span> items found.
</p>
</div>
<div class="my-3">
<!-- Display filtered items in a list -->
<ul data-bind="foreach: filteredItems">
<li data-bind="text: $data"></li>
</ul>
</div>
</div>
</div>
<script>
// Custom filter function
function capitalize(value) {
if (!value) return '';
return value.charAt(0).toUpperCase() + value.slice(1);
}
// Extender to apply the filter
ko.extenders.capitalize = function(target) {
target.capitalized = ko.computed(function() {
return capitalize(target());
});
return target;
};
// ViewModel
function AppViewModel() {
this.firstName = ko.observable('').extend({ capitalize: true });
this.lastName = ko.observable('').extend({ capitalize: true });
var self = this;
// Observable array containing the original data
self.items = ko.observableArray([
'Carrot', 'Apple', 'Banana', 'Orange', 'Broccoli'
]);
// Observable to store the filter criteria
self.filter = ko.observable('');
// Computed observable to filter the items based on the filter criteria
self.filteredItems = ko.computed(function () {
var filter = self.filter().toLowerCase(); // Convert filter criteria to lowercase
if (!filter) {
return self.items(); // If no filter, return all items
} else {
// Filter the items based on the filter criteria
return ko.utils.arrayFilter(self.items(), function (item) {
return item.toLowerCase().indexOf(filter) !== -1; // Case-insensitive match
});
}
});
// Computed observable to get the length of the filtered items
self.filteredItemsLength = ko.computed(function () {
return self.filteredItems().length; // Return the length of the filtered items array
});
}
// Apply bindings
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
This program demonstrates the use of a custom filter function to capitalize the input values in real-time. The
capitalize function capitalizes the first letter of a string, and the
capitalize extender is used to apply this filter to the observables
firstName and lastName. The filtered values are then displayed in the UI using data bindings.
Thank you.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In Knockout.js, filters are commonly used to manipulate and format data before displaying it in the UI. Filters allow you to apply transformations to observable data without modifying the underlying data itself. Here's how you can use filters in Knockout.js:
1. Define a Custom Filter Function
First, define a custom filter function that takes input data and returns the transformed output. You can define this function anywhere in your code, typically within your view model or a separate utility module.
2. Use the extenders Binding Handler
Next, use the extenders binding handler provided by Knockout.js to apply the filter to an observable. The extenders binding handler allows you to extend the behavior of an observable by applying one or more "extensions" or filters.
3. Apply the Filter to Observables
Now, apply the custom filter to your observables when defining them in your view model. You can use the extend function provided by Knockout.js to apply the filter.
4. Bind to the Filtered Data in the UI
Finally, bind to the filtered data in your HTML using the computed property created by the filter. This property will automatically update whenever the original observable changes.
Now bind html and JS code in program.
This program demonstrates the use of a custom filter function to capitalize the input values in real-time. The capitalize function capitalizes the first letter of a string, and the capitalize extender is used to apply this filter to the observables firstName and lastName. The filtered values are then displayed in the UI using data bindings.
Thank you.