How to use filters in knockoutjs?
How to use filters in knockoutjs?
295
21-May-2024
Updated on 23-Oct-2025
Harry
22-May-2024In 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.