JSFiddle - React, Tailwind, and code Playground

by jhorvath

HTML

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap-4-autocomplete/dist/bootstrap-4-autocomplete.min.js"></script>
    <div class="container">
        <div id="parent" class="form-group">
            <label for="myAutocomplete">Country</label>
            <input type="text" id="myAutocomplete" class="form-control" />
        </div>
        <div id="output"></div>
    </div>

CSS

button:focus {
  outline:0;
}

JavaScript

(function ( $ ) {

    let defaults = {
        treshold: 2,
        maximumItems: 8,
        highlightTyped: true,
        highlightClass: "text-primary",
    };

    function createItem(lookup, item, opts, isFirst) {
        let label;
        if (opts.highlightTyped) {
            const idx = item.label.toLowerCase().indexOf(lookup.toLowerCase());
            label = item.label.substring(0, idx)
                    + '<span class="' + expandClassArray(opts.highlightClass) + '">' + item.label.substring(idx, idx + lookup.length) + '</span>'
                    + item.label.substring(idx + lookup.length, item.label.length);
        } else {
            label = item.label;
        }
        return '<button type="button" class="dropdown-item" data-value="' + item.value + '" data-isfirst="' + isFirst + '">' + label + '</button>';
    }

    function expandClassArray(classes) {
        if (typeof classes == "string") {
            return classes;
        }
        if (classes.length == 0) {
            return '';
        }
        let ret = '';
        for (const clas of classes) {
            ret += clas + ' ';
        }
        return ret.substring(0, ret.length - 1);
    }

    function createItems(field, opts) {
        let lookup = field.val();
        if (lookup.length < opts.treshold) {
            field.dropdown('hide');
            return 0;
        }

        let items = field.next();
        items.html('');

        let count = 0;
        let keys = Object.keys(opts.source);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let object = opts.source[key];
            let item = {
                label: opts.label ? object[opts.label] : key,
                value: opts.value ? object[opts.value]: object,
            };
            if (item.label.toLowerCase().indexOf(lookup.toLowerCase()) >= 0) {
                items.append(createItem(lookup, item, opts, count === 0));
                
                if...