Make life easier with
Ease autocomplete component

Easy in use

See the examples and see how easy it is to use the component.

Small size

The main file is approx. 2 KB

Typescript support

If your project uses Typescript, BS4 Autocomplete has type definitions.

See examples

About

Simple to use and lightweight autocomplete/typeahead for Bootstrap 4 and jQuery.

It uses the default Dropdown component from Bootstrap 4 to create the list of autocomplete items.

Originally, I expanded the capabilities of the honatas / bootstrap-4-autocomplete component, but I decided to make my own project out of it.

Usage

Having a defined text field with the identifier "myAutocomplete" you can:

$('#myAutocomplete').autocomplete(options);

Options is a JSON object with the following attributes (in alphabetical order):

compareFnNew

By defining a callback function, you can define your own rules for selecting items for the dropdown list.

Parameters and returns

A parameter with the content from the text field is passed to the function.

dropdownClassNew

It allows you to assign your own CSS class to the native dropdown-menu element.

dropdownOptions
It's the same options from Bootstrap's Dropdown, documented here.
fetchTimeNew

Time (expressed in milliseconds) for the delay until the execution of the onFetchData function.

Default is 500 milisecounds

highlightClass

The class to use when highlighting typed text on items. Only used when highlightTyped is true.

Default is text-primary.

highlightTyped

Wether to highlight (style) typed text on items.

Default is true.

labelClassNew

The name of the CSS class that will be added to the dropdown-item.

maximumItemsChange

How many items you want to show when the autocomplete is displayed.

Note: If the value is set to 0 (zero) all matching results will be displayed.

Default is 5.

onFetchSourceNew

The callback function that is called when text is entered in a text field. Its purpose is to allow you to generate an auto-complete list by sending a request.

Parameters and returns

A parameter with the content from the text field is passed to the function.

The function returns an array of objects (see the description of the source property)

More detailed description in the example further on the page.

onRenderItemNew

The callback function that is called on each matching autocomplete list item. It allows you to program your own way of rendering list items.

Parameters

The functions passed are the current (matching) autocomplete list item and the HTML dropdown list item.

More in the example.

onSelectItem

A callback that is fired every time an item is selected.

Parameters

It receives two parameters: the first is the selected item, the second is the textfield element.

Note that you don't have to use this callback to set the text in the textfield, this is done automatically.

sourceChange

The data from where autocomplete will lookup items to show. This data has to be a JSON array of objects. The default format for this object is:

[
    {
        "label": "label one",
        "value": 1
    },
    {
        "label": "label two",
        "value": 2
    },
    ...
]
                    
treshold

The number of characters that need to be typed on the input in order to trigger the autocomplete.

Default is 4.

Examples

Basic usage:


Basic usage of the extension is based on statically defined data. Definition of the variable color is included as an external file ./colors.js.

The extension options are set so that the drop-down box shows all possible results maximumItems: 0 and allows you to scroll through that list dropdownClass: 'scrolled-dropdown'.

<script src="./colors.js"></script>

<div class="form-group">
    <label for="myAutocomplete">Enter color you like:</label>
    <input type="text" id="myAutocomplete" autocomplete="off" class="form-control" />
</div>
$('#myAutocomplete').autocomplete({
    source: colors,
    treshold: 1,
    maximumItems: 0,
    highlightClass: 'text-danger',
    dropdownClass: 'scrolled-dropdown'
});
.scrolled-dropdown {
    max-height: 200px;
    overflow-y: auto;
}

Custom compare function:


    <script src="./colors.js"></script>
    
    <div class="form-group">
        <label for="myAutocomplete">Enter color you like:</label>
        <input type="text" id="myAutocomplete" autocomplete="off" class="form-control" />
    </div>
    $('#myAutocomplete').autocomplete({
        compareFn: (lookup,item) => item.label.toLowerCase().startsWith(lookup.toLowerCase()),
        source: colors,
        treshold: 1,
        maximumItems: 0,
        highlightClass: 'text-danger',
        dropdownClass: 'scrolled-dropdown'
    });
    .scrolled-dropdown {
        max-height: 200px;
        overflow-y: auto;
    }

Custom dropdown item element render:


<script src="./colors.js"></script>

<div class="form-group">
    <label for="myAutocomplete">Enter color you like:</label>
    <input type="text" id="myAutocomplete" autocomplete="off" class="form-control" />
</div>
$('#myAutocomplete').autocomplete({
    source: colors,
    treshold: 1,
    highlightClass: 'text-danger',
    onRenderItem: (item, html) => {
        let colorBox = $('<span class="myColor" />').css('background-color', item.value);
        html.prepend(colorBox);
    }
});
.myColor {
    display: inline-block;
    width: 1em;
    height: 1em;
    border: #000 solid 1px;
    margin-right: 5px;
}

Fetch source data for autocomplete:


<div class="form-group">
    <label for="myAutocomplete">Enter Your country:</label>
    <input type="text" id="myAutocomplete" autocomplete="off" class="form-control" />
</div>
const getData = async (lookup) => {
    try {
        const response = await fetch(`https://restcountries.eu/rest/v2/name/${lookup}`);
        const data = await response.json();
        return data.map(({name,numericCode}) => ({label: name,value: numericCode}));
    } catch (error) {
        console.log(error);
        alert("HTTP-Error: " + error.status);
        return {};
    }
};

$('#myCountry').autocomplete({
    fetchSource: getData,
    treshold: 1,
    highlightClass: 'text-danger',
});