Have your say in Community Polls: What was/is your greatest motivation to start your own business?

optimize search bar

optimize search bar

alanrichardtex
Shopify Partner
54 3 2

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? 

,
Alan Richard Textiles, The Source for the Finest Home Furnishing Supplies. Distributor for Somfy Motors, Rollease, Velcro, & More!
Reply 1 (1)

topnewyork
Globetrotter
748 124 139

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!

 

Need a Shopify developer?
Hire us at Top New York Web Design
For Shopify Design Changes | Shopify Custom Coding | Custom Modifications
Try Big Bulk Discount To Boost Your Store Sales with Volume/Tier Discount