JSFiddle - React, Tailwind, and code Playground

by anoopsuda

HTML

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
 <div class="input" contenteditable="true" id="countryInput"></div>
    <div class="dropdown" id="countryDropdown"></div>

CSS

.dropdown {
    display: none;
    border: 1px solid #ccc;
    max-height: 100px;
    overflow-y: auto;
}

span {
    display: inline-block;
    margin: 5px;
    padding: 5px;
    background-color: #e0e0e0;
    border: 1px solid #ccc;
    border-radius: 3px;
    cursor: pointer;
}

span:hover {
    background-color: #c0c0c0;
}

span .remove {
    display: inline-block;
    margin-left: 5px;
    cursor: pointer;
}

JavaScript

$(document).ready(function() {
    const countries = ["USA", "Canada", "UK", "Australia", "France", "Germany", "Japan"];
    
    const $input = $("#countryInput");
    const $dropdown = $("#countryDropdown");
    
    // Populate the dropdown with country items
    function populateDropdown() {
        $dropdown.empty();
        countries.forEach(function(country) {
            if ($input.text().indexOf(country) === -1) {
                const $item = $("<div>").text(country);
                $item.on("click", function() {
                    addCountryToInput(country);
                    $item.remove();
                });
                $dropdown.append($item);
            }
        });
    }

    function addCountryToInput(country) {
        const $span = $("<span contenteditable='false'>").text(country);
        const $remove = $("<span class='remove'>x</span>");
        
        $remove.on("click", function() {
            $span.remove();
            $dropdown.append($("<div>").text(country).on("click", function() {
                addCountryToInput(country);
                $(this).remove();
            }));
        });
        
        $span.append($remove);
        $input.append($span);
    }

    // Show the dropdown when the user types a letter
    $input.on("input", function() {
        $dropdown.show();
        populateDropdown();
    });

    // Hide the dropdown when clicking outside the input or dropdown
    $(document).on("click", function(event) {
        if (!$input.is(event.target) && !$dropdown.is(event.target) && $dropdown.has(event.target).length === 0) {
            $dropdown.hide();
        }
    });
});