optimize search bar

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!

Hi @alanrichardtex ,

Shopify default search created to search product title and description therefore search bar don’t show any results.

You can add SKU details the part of the description and it will start showing in search result.

Hope this will helps…

when I try adding that code to the bottom on that json file it says it is not valid and wont save.