Countries Auto Complete Example

This article demonstrates how an auto complete can be implemented ny using jquery. The API end point is described below.

Countries Auto Complete API 

url: http://usmanlive.com/wp-json/api/countries 

It accepts a querystring parameter named q and will return the array of coutries which matches the provided parameter e.g. 

http://usmanlive.com/wp-json/api/countries?q=ak will return [“Kazakhstan”,”Pakistan”] use this api to practice autocomplete.

Try Countries API yourself

Demo

The output would look like this where you can type and suggestions would appear

Source Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Autocomplete with Loader</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .autocomplete-container {
            position: relative;
            width: 250px;
        }
        #country {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            padding-right: 30px; /* Make space for loader */
        }
        .autocomplete-list {
            position: absolute;
            top: 100%;
            left: 0;
            width: 100%;
            border: 1px solid #ccc;
            background: white;
            max-height: 200px;
            overflow-y: auto;
            display: none;
            z-index: 1000;
        }
        .autocomplete-item {
            padding: 8px;
            cursor: pointer;
        }
        .autocomplete-item:hover, .autocomplete-item.active {
            background: #f0f0f0;
        }
        /* Loader styles */
        .loader {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            width: 16px;
            height: 16px;
            border: 3px solid #ccc;
            border-top-color: #007bff;
            border-radius: 50%;
            animation: spin 0.7s linear infinite;
            display: none;
        }
        @keyframes spin {
            from { transform: translateY(-50%) rotate(0deg); }
            to { transform: translateY(-50%) rotate(360deg); }
        }
    </style>
</head>
<body>

    <div class="autocomplete-container">
        <input type="text" id="country" placeholder="Type to search...">
        <div class="loader"></div>
        <div id="autocomplete-list" class="autocomplete-list"></div>
    </div>

    <script>
        $(document).ready(function () {
            let selectedIndex = -1; // Track the selected index for keyboard navigation

            $("#country").on("input", function () {
                let query = $(this).val().trim();
                if (query.length === 0) {
                    $("#autocomplete-list").hide();
                    return;
                }

                $(".loader").show(); // Show loader when API call starts

                $.ajax({
                    url: "http://usmanlive.com/wp-json/api/countries",
                    dataType: "json",
                    data: { q: query },
                    success: function (data) {
                        $(".loader").hide(); // Hide loader when data is received
                        let suggestions = data.map(item => `<div class="autocomplete-item">${item}</div>`).join("");
                        if (suggestions) {
                            $("#autocomplete-list").html(suggestions).show();
                            selectedIndex = -1; // Reset selection
                        } else {
                            $("#autocomplete-list").hide();
                        }
                    },
                    error: function () {
                        $(".loader").hide(); // Hide loader on error
                        $("#autocomplete-list").hide();
                    }
                });
            });

            // Click event for selecting an item
            $(document).on("click", ".autocomplete-item", function () {
                $("#country").val($(this).text());
                $("#autocomplete-list").hide();
            });

            // Hide dropdown if user clicks outside
            $(document).on("click", function (e) {
                if (!$(e.target).closest(".autocomplete-container").length) {
                    $("#autocomplete-list").hide();
                }
            });

            // Keyboard navigation
            $("#country").on("keydown", function (e) {
                let items = $("#autocomplete-list .autocomplete-item");
                if (items.length === 0) return;

                if (e.key === "ArrowDown") {
                    e.preventDefault();
                    selectedIndex = (selectedIndex + 1) % items.length;
                    items.removeClass("active").eq(selectedIndex).addClass("active");
                } else if (e.key === "ArrowUp") {
                    e.preventDefault();
                    selectedIndex = (selectedIndex - 1 + items.length) % items.length;
                    items.removeClass("active").eq(selectedIndex).addClass("active");
                } else if (e.key === "Enter") {
                    e.preventDefault();
                    if (selectedIndex >= 0) {
                        $("#country").val(items.eq(selectedIndex).text());
                        $("#autocomplete-list").hide();
                    }
                }
            });
        });
    </script>

</body>
</html>