#Database #Collection #query #filter #debounce #dropdown #Example
![](https://static.wixstatic.com/media/a27d24_fee97466db714860b2cdc5085c1d3787~mv2.png/v1/fill/w_980,h_576,al_c,q_90,usm_0.66_1.00_0.01,enc_auto/a27d24_fee97466db714860b2cdc5085c1d3787~mv2.png)
Demonstrates
Links for this example
About this example
Add search functionality to your site by adding input elements to the page and then adding code to enable the search.
There are different ways you can let your users search your collection. This example uses the following input options:
Adding an input field where a user enters a search string.
Adding a dropdown where a user selects from a list.
To add persistence to the user's search, see the next Example: Saved Search.
For those of you wondering how to add another dropdown filter, it's something like this:
export function iContinent_change(event) {
filter(lastFilterTitle, $w('#iContinent').value, lastFilterCountry);
}
export function iCountry_change(event) {
filter(lastFilterTitle, lastFilterContinent, $w('#iCountry').value);
}
function filter(title, continent, country) {
if (lastFilterTitle !== title ||
lastFilterContinent !== continent ||
lastFilterCountry !== country) {
let newFilter = wixData.filter();
if (title)
newFilter = newFilter.contains('articleTitle', title);
if (continent)
newFilter = newFilter.contains('continent', continent);
if (country)
newFilter = newFilter.contains('authorCountry', country);
$w('#dataset1').setFilter(newFilter);
lastFilterTitle = title;
lastFilterContinent = continent;
lastFilterCountry = country;
}
}
Make sure you connect the dropdown components to the appropriate event handlers: iContinent_change() and iCountry_change().
Hello! I tried to model a data search based off of this example, and include a slider as a filter. I can't seem to find the error in my code but neither the drop downs or the slider are filtering the dataset. Would you mind taking a look??
website link: https://www.superradicals.com/copy-2-of-fractions
What works: The text search. The dropdowns populate the appropriate options. (the drop-downs
look like they work on the site only because I have them connected to the data via the wix filter tool - not through code!)
What doesn't work: The dropdown search filter through code (see below). The slider doesn't work either!! Should use values 1-3 to filter through dataset.
import wixData from "wix-data"; $w.onReady(() => { loadTypes(); loadAges(); }); let lastFilterTitle; let lastFilterType; let lastFilterAge; let lastFilterDifficulty; let debounceTimer; export function iSearch_keyPress(event, $w) { if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = undefined; } debounceTimer = setTimeout(() => { filter($w('#iSearch').value, lastFilterType, lastFilterAge, lastFilterDifficulty); }, 200); } export function iResource_change(event, $w) { filter(lastFilterType, $w('#iResource').value), lastFilterAge, lastFilterDifficulty; } export function slider1_change(event, $w) { filter(lastFilterTitle, lastFilterType, lastFilterAge, $w('#slider1').value); } export function iGradelevel_change(event, $w) { filter(lastFilterTitle, lastFilterType, $w('#iGradeLevel').value, lastFilterDifficulty); } function filter(title, type, age, difficulty) { console.log("title = " + title + "type = " + type + "age =" + age + "difficulty max = " + difficulty); if (lastFilterTitle !== title || lastFilterType !== type || lastFilterAge !== age || lastFilterDifficulty !== difficulty) { let newFilter = wixData.filter(); if (title) newFilter = newFilter.contains('title', title); if (type) newFilter = newFilter.contains('type', type); if (age) newFilter = newFilter.contains('newField', age); if (difficulty) newFilter = newFilter.contains('difficultyMax', difficulty); $w('#dataset1').setFilter(newFilter); lastFilterType = type; lastFilterTitle = title; lastFilterAge = age; lastFilterDifficulty = difficulty; console.log("title = " + title + "type = " + type + "age =" + age + "difficulty max = " + difficulty); } } function loadTypes() { // Run a query that returns all the items in the collection wixData.query("Tangibles") // Get the max possible results from the query .limit(1000) .ascending("type") .distinct("type") .then(results => { let distinctList = buildOptions(results.items); // unshift() is like push(), but it prepends an item at the beginning of an array distinctList.unshift({ "value": '', "label": 'All Resources' }); // Call the function that builds the options list from the unique titles $w("#iResource").options = distinctList; }); } function loadAges() { // Run a query that returns all the items in the collection wixData.query("Tangibles") // Get the max possible results from the query .limit(1000) .ascending("newField") .distinct("newField") .then(results => { let distinctList = buildOptions(results.items); // unshift() is like push(), but it prepends an item at the beginning of an array distinctList.unshift({ "value": '', "label": 'All Grade Levels' }); // Call the function that builds the options list from the unique titles $w("#iGradeLevel").options = distinctList; }); } function buildOptions(items) { return items.map(curr => { // Use the map method to build the options list in the format {label:uniqueTitle, value:uniqueTitle} return { label: curr, value: curr }; }); }
You can use the split() function to split a string into an array of words (substrings). Assuming that inputStr is your input string, you can do a really simple slitting of the string like this:
let arrayOfWords = inputStr(" ");
A better way, albeit slightly more complicated, would be to use a regular expression to split a string that even has punctuation:
let arrayOfWords = inputStr.match(/\b(\w+)\b/g);
@Yisrael (Wix) could you help me on this subject? Let me explain my problem:
I want my user to be able to put a whole question in the input box and search for the best solution based on keywords.
Example:
Question Input: "My landlord raised the rent in 30%. Is this fair?"
Answer: No this is not correct (keywords: raise; above average; big raise; above contract; etc)
I tried to use the search bar and apps on wix for my search bar and they try to find the specific words and if you input a big phrase they dont show anything.
They work if you put: "rent" or "landlord" but not if you put the whole phrase
My idea was to
1) split the input text in many different buckets. Example:
"My"; "landlord"; "raised"; "the"; "rent"; "in"; "30%"; "Is"; "this"; "fair"; "My landlord"; "landlord raised"; "raised the"; "the rent"; "rent in"; "in 30%"; "30% is"; "is that"; "that fair"
2) create a loop to search all these in the database using "Search and contains"
3) sum 1 to each word that i find
4) show answers from biggest to smallest, where the biggest has more words (or phrases) that match with the key words
My problem is that i dont know how to split by " " (space) a phrase. Could you help me with that?
Thank you,
Applied code as specified and it works great except...
When selecting a Moku (dropdown filter) it shows all the Mokus in that category PLUS the "unpublished' profiles. Unpublished/published profiles are indicated with Boolean in the database. How can I filter the Mokus in the dropdown to ONLY
include the published profiles.
https://www.leiofkauai.com/people
ex Laura is technically unpublished since she was not activated in the database via the boolean (active column). Yet she does not show in the default load page but on the search dropdown filter.
Second problem: 'All Mokus" show a blank page, what am I missing?
I have tried multiple times, and just can't get my search or drop down to work. Please help me. Here's my site and the code. https://www.bwchurches.org/churchlist
import wixData from "wix-data";
$w.onReady(() => {
loadCities();
});
let lastFilterTitle;
let lastFilterCity;
let debounceTimer;
export function ChurchesSearch_keyPress(event, $w) {
if (debounceTimer){
clearTimeout(debounceTimer);
debounceTimer = undefined;
}
debounceTimer = setTimeout(() => {
filter($w('#ChurchesSearch').value, lastFilterCity);
}, 500);
}
export function CityFilter__1(event, $w) {
filter(lastFilterTitle, $w('#CityFilter').value);
}
function filter(title, city) {
if (lastFilterTitle !== title || lastFilterCity !== city){
let newFilter = wixData.filter();
if (title)
newFilter = newFilter.contains('Church', city);
if (city)
newFilter = newFilter.contains('city', city);
$w('#dynamicDataset').setFilter(newFilter);
lastFilterTitle = title;
lastFilterCity = city;
}
}
function loadCities() {
wixData.query('Cities')
.find()
.then(res => {
let options = [{"value": '', "label": 'All Cities'}];
options.push(...res.items.map(city => {
return {"value": city.title, "label": city.title};
}));
$w('#CityFilter').options = options;
});
}
Hi @Yisrael (Wix) and the rest,
The code works nicely, but how do I use e referenced field for my drop-down filter? I read about query and include, and I cannot make it work, don't know how to integrate it into my code. link to the page in my site https://editor.wix.com/html/editor/web/renderer/edit/ab0c6988-0c60-4b82-aef1-aa3d1409088c?metaSiteId=fda237cb-963e-44ee-ad8d-e272c64e06c4&editorSessionId=48AE4F59-5C22-4D55-AC4C-58452362D8F3
Your help please?
תודה :) efrat
@Yisrael (Wix)
Hello, great tutorial, I have got the search bar all working perfectly but cant get the dropdown to work correctly, It is populated with the categories I want, but clicking them seems to do absolutely nothing!
Could you please tell me where i'm going wrong!?
Thanks!
Wix editor link:
https://editor.wix.com/html/editor/web/renderer/edit/ba7a58e7-d8fc-4e11-9441-71555f0217f9?metaSiteId=cd5442be-8895-438b-86bc-ef8350e36ea4&editorSessionId=2cfbfcc8-6b20-484e-89fa-b539751f8db1&referralInfo=my-account
Is there anyway where visitors search the website by keywords ?
The new site search app is not searching by keywords available on the website? Is it under development or it work like this - You can find the new site search in "MORE" section. Please let me know
I need to add another snippet of code to further refine my search filter on my real estate website. I added a "Off Market" boolean field to my database of properties so I can quickly and easily check off which properties are no longer on the market.
Here is my currently functioning code that does NOT exclude "off market" properties from the search filter:
let debounceTimer; export function searchINPUT_keyPress(event) { if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = undefined; } debounceTimer = setTimeout(() => { filter($w('#searchINPUT').value); }, 200); } let lastFilterTitle; function filter(title) { if (lastFilterTitle !== title) { $w('#dataset1').setFilter(wixData.filter().contains('title', title)); lastFilterTitle = title; } }
Here are 2 (unsuccessful) examples of my code trying to refine the search filter so that it does not include properties marked as off market:
let lastFilterTitle; function filter(title) { if (lastFilterTitle !== title) { $w('#dataset1').setFilter(wixData.filter() .eq('offMarket', false) .contains('title', title)); lastFilterTitle = title; } }
let lastFilterTitle; function filter(title) { if (lastFilterTitle !== title) { $w('#dataset1').setFilter(wixData.filter() .not('offMarket', true) .contains('title', title)); lastFilterTitle = title; } }
**QUESTION - WHAT DO I NEED TO DO IN ORDER FOR MY SEARCH FILTER TO EXCLUDE MY PROPERTIES MARKED AS "OFF MARKET"??
Fairly new to Wix and enjoying diving deeper into it. I'm trying to get a simple dropdown menu calling from a data set to update the repeater.. Everything seems to be working, but the repeater doesn't update / the filters don't seem to be working. Can someone help me take a look at this and see what I'm missing?
I've compared over and over to the reference editor site provided and I can't find anything else that is different. I don't want the search text field, just the dropdown function to filter by a few brand..
I haven't altered the code provided. I matched all elements names, ID's and field keys to the demo.. I'm at at dead end though. Thank you for any help!
https://editor.wix.com/html/editor/web/renderer/edit/638468a8-2f98-4669-a6e4-4ec97c922015?metaSiteId=2ae5c5f6-f65e-4c59-812b-7a2fc0a6f865&editorSessionId=df210aba-b59a-46d2-9e7c-db2966a4e045&referralInfo=dashboard
I opened the example in my editor and did not change anything, but I get errors in preview when doing a search:
TypeError: Property description must be an object. ARTICLES. Line 31.
It seems something is broken on this line:
$w('#dataset1').setFilter(newFilter);
I have the same problem with my Corvid search, there I also can't get the search running. I guess this is a bug in wix? As I had no problems running this example just a few weeks back?
Update: It works in Firefox - not in Safari...
I'm getting this to work with text fields, but could anyone help me with using this on a dataset entry for a number value? @Yisrael (Wix) ?
@Yisrael (Wix) Thank you so much for the example, it's been EXTREMELY helpful. I was able to get everything working and add more filters, but am perplexed with why the last filter isn't working. I'd really appreciate any help you can provide.
Specifically looking for help on the priceRange dropdown
Site edit URL: https://editor.wix.com/html/editor/web/renderer/edit/e6c5231d-cd19-4fa9-bdda-f021323b43c5?metaSiteId=c94a0b40-101b-4c7a-bb05-dfd6e2eec815&editorSessionId=75ffa5fa-25c8-4a47-b266-ea1938b6e7bd&referralInfo=dashboard
Code:
import wixData from "wix-data"; $w.onReady(() => { loadBedrooms(); loadGuests(); loadPrice(); }); let lastFilterTitle; let lastFilterBedrooms; let lastFilterGuests; let lastFilterPrice; let debounceTimer; export function iTitle_keyPress(event, $w) { if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = undefined; } debounceTimer = setTimeout(() => { filter($w('#iTitle').value, lastFilterBedrooms, lastFilterGuests); }, 200); } export function dropdownBedrooms_change(event) { filter(lastFilterTitle, $w('#dropdownBedrooms').value, lastFilterGuests); } export function dropdownGuests_change(event) { filter(lastFilterTitle, lastFilterBedrooms, $w('#dropdownGuests').value, lastFilterPrice); } export function priceRange_change(event) { filter(lastFilterTitle, lastFilterBedrooms, lastFilterGuests, $w('#priceRange').value); } function filter(title, bedrooms, guests, price) { if (lastFilterTitle !== title || lastFilterBedrooms !== bedrooms || lastFilterGuests !== guests || lastFilterPrice !== price){ let newFilter = wixData.filter(); if (title) newFilter = newFilter.contains('propertyName', title); if (bedrooms) newFilter = newFilter.ge('ofRooms', bedrooms); if (guests) newFilter = newFilter.ge('ofGuests', guests); if (price) newFilter = newFilter.ge('priceLow', price).or('priceHigh', price); $w('#dataset1').setFilter(newFilter); lastFilterTitle = title; lastFilterBedrooms = bedrooms; lastFilterGuests = guests; lastFilterPrice = price; } } function loadGuests(){ wixData.query('ofGuests') .find() .then(res => { let options = [{"value": '', "label": 'Any'}]; options.push(...res.items.map(guests =>{ return {"value": guests.title, "label":guests.title}; })); $w('#dropdownGuests').options = options; }); } function loadBedrooms () { wixData.query('ofRooms') .find() .then(res => { let options = [{"value": '', "label": 'Any'}]; options.push(...res.items.map(bedrooms => { return {"value": bedrooms.title, "label": bedrooms.title}; })); $w('#dropdownBedrooms').options = options; }); } function loadPrice () { wixData.query('priceLow') .find() .then(res => { let options = [{"value": '', "label": 'Any'}]; options.push(...res.items.map(price => { return {"value": price.title, "label": price.title}; })); $w('#priceRange').options = options; }); }
Is there a way to add two filters to a search bar (input field, not dropdown)? For instance, if someone wanted to type in an article title or a country in the search bar in the example used in this tutorial, how would you do that? I know the following code is for the search bar only and I tried playing around with it, but nothing I did worked. If someone could help me figure this out, I'd greatly appreciate it. Thank you!
import wixData from 'wix-data';
let debounceTimer; export function iTitle_keyPress(event, $w) { if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = undefined; } debounceTimer = setTimeout(() => { filter($w('#iTitle').value); }, 200); }
let lastFilterTitle; function filter(title){ if (lastFilterTitle !== title) { $w('#dataset1').setFilter(wixData.filter().contains('articleTitle', title)); lastFilterTitle = title; } }
Thank you for the great Tutorials, this was my first really help to understand how it works, but I am struggeling because it do not work for me because I use References for the Values
How can I set the Filter with the References insteat to use Text (String) ?
I have seen there is a demand to use Forein-Key in Database which sould be Filterable but no Tutorial exist so far.
This would be absolutly great if this is possible!!! It a must have I think :-)
@Yisrael (Wix) I am off on another tangent of study. Trying to now make the two drop downs dependent. I understand the cascading form, but not sure how to actually implement into a filter code. Can you push me in a general direction?
Here is my latest attempt...just not working. Note that the search dropdown database is misspelled on purpose to differentiate (Catagory) For some reason my dropdown populating is not loading
$w.onReady(() => { loadCatagory(); loadProfileCategories(); }) let lastFilterCombination; let lastFilterCategory; let lastFilterSection;
let debounceTimer; export function iTitle_keyPress (event, $w) { if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = undefined; } debounceTimer = setTimeout(() => { filter($w('#iTitle').value, lastFilterCategory, lastFilterSection); }, 500); } export function iCategory_change(event, $w) { filter(lastFilterCombination, $w('#iCategory').value), lastFilterSection; } export function iSection_change_(event, $w) { filter(lastFilterCombination, lastFilterCategory, $w('#iSection').value); }
function filter(combination, category, section) { if (lastFilterCombination !== combination || lastFilterCategory !== category || lastFilterSection !== section) { let newFilter = wixData.filter(); if (combination) newFilter = newFilter.contains('combination', combination); if (category) newFilter = newFilter.contains('category', category); if (section) newFilter = newFilter.contains('section', section); $w('#dataset6').setFilter(newFilter); lastFilterCombination = combination; lastFilterCategory = category; lastFilterSection= section; } function filter(combination, category, section) { if (lastFilterCombination !== combination || lastFilterCategory !== category || lastFilterSection !== section) { let newFilter = wixData.filter(); if (combination) newFilter = newFilter.contains('combination', combination); if (category) newFilter = newFilter.contains('category', category); if (section) newFilter = newFilter.contains('section', section); $w('#dataset6').setFilter(newFilter); lastFilterCombination = combination; lastFilterCategory = category; lastFilterSection = section; } function loadCatagory() { wixData.query('Catagory') .find() .then(res => { let options = [{"value": '', "label": 'ALL CATEGORIES'}]; options.push(...res.items.map(Catagory => { return {"value": Catagory.title, "label": Catagory.title}; })); $w('#iCategory').options = options; }); }
function loadProfileCategories() { wixData.query('ProfileCategories') .find() .then(res => { let options = [{"value": '', "label": 'ALL SECTIONS'}]; options.push(...res.items.map(section => { return {"value": section.title, "label": section.title}; })); $w('#iSection').options = options; }); }}
Hello,
Can this be done to search a products in the productGallery element of the Store page as well? I can see it's working using the Repeater page element now.
When AdditionalInfoSections will be available for sorting and filtering?
Thanks
Sweet can’t wait to try this one out, thanks