I watched the youtube video on creating a search bar for a dynamic page. It was a great video. But I am new to Javascript. I have gotten it to work-ish, but however when the search bar is null or empty, 'after' typing something in it, the repeater contents get scrambled. For some reason it doesn't stay in the order or goes back to the order before the search or the order outlined in the sorting method. After a user clears out the search box after a search is done. Any help or suggestion would be greatly appreciated.
Thanks,
Aaron
import wixData from 'wix-data';
$w.onReady(function () {
$w("#magazineRepeater").onItemReady(($item, itemData)=>{
$item("#contents").text = itemData.contents;
})
$w("#magazineRepeater").onItemReady(($item, itemData)=>{
$item("#contents").text = itemData.contents;
})
async function search() {
const query = $w("#searchQueryInput").value;
const contentsQuery = wixData.query("MagazineArchives").contains("contents", query);
const magDataQueryResults = await contentsQuery
.find();
const MagazineArchives = magDataQueryResults.items;
$w("#magazineRepeater").data = MagazineArchives;
}
$w("#searchButton").onClick(search);
let throttle;
$w('#searchQueryInput').onInput(() => {
clearTimeout(throttle);
throttle = setTimeout(() => {
search();
}, 500);
})
});
Before:
After:
Hi Aaron, Thanks for checking out the channel and sharing your project! What I think is happening here is that when you clear the search bar essentially the search function is running with a query of "" (empty string). To prevent this behavior you can add a condition to the search function or to the event listener to detect this scenario and run custom logic (such as a standard query with no filters). For example:
//inside search function let contentsQuery; if (query === ""){ //or !query contentsQuery = wixData.query("MagazineArchives"); }
If you need a specific sort, you can also utilize the .ascending or .descending methods.
Hope that helps! Eitan