When you have a database collection with lots of content, site visitors need an easy way to find what they're looking for. You can add powerful search and filtering capabilities to your site, transforming static content displays into interactive, user-friendly experiences.
This tutorial demonstrates how to build:
You'll learn to query collections, handle user input, and create interfaces that enhance the user experience.
We'll use the following steps to query a database collection and dynamically display matching results:
The code in this article was written using the following module versions:
Learn how to install npm packages in the editor or using the CLI.
You need to note the following points before starting to code:
This step sets up the user interface elements needed for search and filtering functionality.
Add a repeater to your page. Set the repeater ID to articlesList.
Inside the repeater, add:
itemImage.itemCountry and itemContentAdd an input field for searching. Set the input ID to inputTitle.
Add a dropdown element. Set the dropdown ID to inputContinent.
This step retrieves all items from your collection and prepares them for display. When the page loads, you'll display all the items before any filtering is applied.
To query a collection, you'll need to get the collection ID. The way you get the ID depends on the editor you're using:
Now that you have the collection ID, you can query your data:
@wix/data module, which provides the query() method for retrieving collection data. Also, save the collection ID to the collectionName variable.The query returns an array of items, where each item represents an item from your collection. Collection field IDs become object properties, so fields such as image, country, content appear as properties with the same names in each result object.
Use the onItemReady() event handler to map your collection field values to specific repeater elements. This event runs automatically for each new element in the repeater's .data array.
The handler receives an $item selector, which selects specific instances of repeated elements. In this example, image, country, and content are field IDs from your database collection:
continent values. Add a default option labeled "All" with the value All. This option allows site visitors to view all items, unfiltered.initRepeater(), loadAllResults(), and initDropdown() functions in the $w.onReady() handler:This step adds the interactive functionality that allows site visitors to search and filter the displayed content in real time.
buildFilterAndPopulateRepeater(). It filters your repeater results by checking if the "country" field contains the input text. When a dropdown value is selected, this function filters the collection and updates the repeater. Also, set the repeater's data property to your collection results:Here's the complete working code: