Shopify themes, liquid, logos, and UX
Hi, on my site alanrichardtextiles.com we have many products that people search for by their sku or product number. My issue is that when you type in a sku it says no results found. But when you click enter then it shows up. How can I make it so that it pulls up products based on their sku when someone types it into the search bar?
Hello, @alanrichardtex
1) Go to Online Store
2) Edit Code
3) Find en.default.json file
4) Add the following code in the bottom
const searchBar = document.getElementById("search-bar");
const suggestionsBox = document.getElementById("suggestions");
searchBar.addEventListener("input", function () {
const query = searchBar.value.trim(); // User input
if (query.length > 2) {
// Fetch suggestions from backend
fetch(`/api/search?sku=${query}`) // Replace with your API endpoint
.then((response) => response.json())
.then((data) => {
// Clear previous suggestions
suggestionsBox.innerHTML = "";
if (data.length > 0) {
suggestionsBox.style.display = "block";
// Loop through results and display them
data.forEach((item) => {
const suggestion = document.createElement("div");
suggestion.textContent = `${item.name} (SKU: ${item.sku})`;
// On click, fill the input and hide suggestions
suggestion.addEventListener("click", () => {
searchBar.value = item.sku;
suggestionsBox.style.display = "none";
});
suggestionsBox.appendChild(suggestion);
});
} else {
suggestionsBox.style.display = "none";
}
})
.catch((error) => {
console.error("Error fetching suggestions:", error);
});
} else {
suggestionsBox.style.display = "none";
}
});
// Hide suggestions when clicking outside
document.addEventListener("click", (e) => {
if (!suggestionsBox.contains(e.target) && e.target !== searchBar) {
suggestionsBox.style.display = "none";
}
});
Thanks!
As 2024 wraps up, the dropshipping landscape is already shifting towards 2025's trends....
By JasonH Nov 27, 2024Hey Community! It’s time to share some appreciation and celebrate what we have accomplis...
By JasonH Nov 14, 2024In today’s interview, we sat down with @BSS-Commerce to discuss practical strategies f...
By JasonH Nov 13, 2024