Bootstrap Typeahead

We will discover how to construct typeaheads with Bootstrap in this article.


Creating Typeaheads with Bootstrap

Typeahead input fields have gained significant popularity in modern web forms. Their primary purpose is to enhance the user experience by providing hints or a list of possible choices based on the text entered while filling out a form or conducting a search, similar to Google's instant search feature.

Utilizing typeahead functionality not only improves user experience but also saves time and reduces potential errors since users are less likely to make spelling mistakes. However, it's important to note that the Typeahead plugin has been removed from Bootstrap (v3.0+) in favor of Twitter typeahead.

Twitter typeaheads is a robust and speedy autocomplete library inspired by twitter.com's autocomplete search. To implement Twitter typeaheads, you need to download typeahead.js from their official page (https://twitter.github.io/typeahead.js/) and include it in your project. Once integrated, you can easily turn any text-based <input> element into a typeahead.

It's worth mentioning that Twitter typeaheads require jQuery 1.9+ to function correctly, and there is no non-jQuery version available.

Creating Twitter Typeahead with Local Dataset

If you want to create Twitter typeahead with a local dataset, the following example will guide you through the process.

<script>
$(document).ready(function () {
    // Defining the local dataset
    var countries = ['America', 'Africa', 'Brazil', 'Belgium', 'India', 'Ireland', 'Indonesia'];

    // Constructing the suggestion engine
    var countries = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: countries
    });

    // Initializing the typeahead
    $('.typeahead').typeahead({
        hint: true,
        highlight: true, /* Enable substring highlighting */
        minLength: 1 /* Specify minimum characters required for showing suggestions */
    },
    {
        name: 'country',
        source: countries
    });
});
</script>

Note: In this context, Bloodhound serves as the typeahead.js suggestion engine. It offers great flexibility and advanced features like prefetching remote data and fast lookups through intelligent caching using the browser's local storage.

Tip: To prevent default browser menus from appearing over the Bootstrap type-ahead dropdown, set autocomplete=off for the input box.


Creating Twitter Typeahead External Dataset

Additionally, you can specify an external dataset through a URL pointing to a JSON file that contains an array of datums. Each individual unit in these datasets is called a datum.

<script>
$(document).ready(function () {
    // Sonstructs the suggestion engine
    var countries = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        // The url points to a json file that contains an array of country names
        prefetch: 'countries.json'
    });

    // Initializing the typeahead with remote dataset without highlighting
    $('.typeahead').typeahead(null, {
        name: 'countries',
        source: countries,
        limit: 10 /* Specify max number of suggestions to be displayed */
    });
});
</script>

FAQ

What is Bootstrap Typeahead?

Bootstrap Typeahead is a component in the Bootstrap framework that provides an interactive suggestion dropdown as users type into an input field. It's commonly used for implementing autocomplete functionality in web applications.

How do I include Bootstrap Typeahead in my project?

To include Bootstrap Typeahead in your project, you need to include the Bootstrap CSS and JavaScript files, along with the Typeahead-specific JavaScript file. Here's an example of how to include them:

<!-- Include Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<!-- Include Bootstrap JS (Popper.js is required) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<!-- Include Typeahead JS -->
<script src="path/to/bootstrap-typeahead.js"></script>

How do I initialize Bootstrap Typeahead on an input field?

You can initialize Bootstrap Typeahead on an input field using jQuery and JavaScript. Here's an example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape']
        });
    });
</script>

Can I use remote data sources with Bootstrap Typeahead?

Yes, you can use remote data sources with Bootstrap Typeahead. You need to provide a function that fetches data from a remote source and then use that function as the source parameter when initializing Typeahead. Here's an example using the $.ajax function:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: function (query, process) {
                return $.ajax({
                    url: 'path/to/remote/source',
                    type: 'GET',
                    data: { query: query },
                    dataType: 'json',
                    success: function (data) {
                        return process(data);
                    }
                });
            }
        });
    });
</script>

How can I customize the appearance of the Bootstrap Typeahead dropdown?

You can customize the appearance of the Bootstrap Typeahead dropdown by using CSS to target the relevant classes. The dropdown itself is generated by Bootstrap, so you can modify its styling by overriding Bootstrap's default styles. For example:

/* Customize Typeahead dropdown */
.tt-dropdown-menu {
    background-color: #f5f5f5;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 8px;
}

How can I customize the number of suggestions displayed in the Bootstrap Typeahead dropdown?

By default, Bootstrap Typeahead displays 8 suggestions in its dropdown. To customize the number of suggestions, you can use the items option when initializing Typeahead. For example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'],
            items: 5 // Display 5 suggestions in the dropdown
        });
    });
</script>

How can I handle the selection of an item from the Bootstrap Typeahead dropdown?

You can use the change event to handle the selection of an item from the Typeahead dropdown. This event fires when the user selects an item from the dropdown. Here's an example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'],
            change: function (item) {
                // Handle the selected item here
                console.log('Selected: ' + item);
            }
        });
    });
</script>

Can I customize the delay before the Bootstrap Typeahead dropdown appears after typing?

Yes, you can customize the delay using the delay option. The delay option specifies the number of milliseconds to wait after a keystroke before showing the dropdown. Here's an example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'],
            delay: 500 // Show dropdown after 500ms of typing
        });
    });
</script>

Can I customize the behavior of Bootstrap Typeahead to not automatically select the first suggestion?

Yes, you can customize this behavior using the autoSelect option. By default, Typeahead automatically selects the first suggestion as you navigate the dropdown using the arrow keys. If you set autoSelect to false, the first suggestion won't be automatically selected. Here's an example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'],
            autoSelect: false // Do not automatically select the first suggestion
        });
    });
</script>

Can I customize the template of each suggestion in the Bootstrap Typeahead dropdown?

Yes, you can customize the template of each suggestion using the template option. This allows you to control the HTML structure and appearance of each suggestion in the dropdown. Here's an example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'],
            template: '<p><strong>{{value}}</strong> - This is a fruit</p>'
        });
    });
</script>

In this example, {{value}} is a placeholder that will be replaced with the suggestion's value.

Can I use custom data sources like arrays of objects with Bootstrap Typeahead?

Yes, you can use custom data sources like arrays of objects with Bootstrap Typeahead. You need to provide a function that filters and processes the data accordingly. Here's an example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        var fruits = [
        { id: 1, name: 'Apple' },
        { id: 2, name: 'Banana' },
        { id: 3, name: 'Cherry' },
        { id: 4, name: 'Date' },
        { id: 5, name: 'Fig' },
        { id: 6, name: 'Grape' }
    ];

        $('#myInput').typeahead({
            source: function (query, process) {
                var matches = [];
                $.each(fruits, function (index, fruit) {
                    if (fruit.name.toLowerCase().indexOf(query.toLowerCase()) !== -1) {
                        matches.push(fruit);
                    }
                });
                return process(matches);
            },
            displayText: function (item) {
                return item.name;
            }
        });
    });
</script>

Is it possible to use Bootstrap Typeahead with Bootstrap 5?

Bootstrap 5 dropped the support for Typeahead component. However, you can still use Bootstrap 4 along with Typeahead.

How can I handle the selection event when a suggestion is clicked in the Bootstrap Typeahead dropdown?

You can handle the selection event when a suggestion is clicked using the select event. This event provides you with the selected item's value and related data. Here's an example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'],
            onSelect: function (item) {
                // Handle the selected item here
                console.log('Selected: ' + item);
            }
        });
    });
</script>

Is it possible to customize the minimum characters required before Bootstrap Typeahead shows suggestions?

Yes, you can customize the minimum characters required before Typeahead starts showing suggestions using the minLength option. For example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'],
            minLength: 2 // Show suggestions after typing at least 2 characters
        });
    });
</script>

Can I control the order of suggestions in the Bootstrap Typeahead dropdown?

Yes, you can control the order of suggestions by providing a custom sorting function to the source option. Here's an example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'],
            sorter: function (items) {
                return items.sort(); // Sort suggestions alphabetically
            }
        });
    });
</script>

You can replace the sorting function with any custom logic you need.

Can I prevent Bootstrap Typeahead from opening on certain conditions?

Yes, you can control when the Bootstrap Typeahead dropdown opens by using the open method and returning false in certain conditions. For example:

<input type="text" id="myInput" class="form-control">

<script>
    $(document).ready(function () {
        $('#myInput').typeahead({
            source: ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape']
        });

        $('#myInput').on('focus', function () {
            if (someCondition) {
                $(this).typeahead('open');
            } else {
                $(this).typeahead('close');
            }
        });
    });
</script>

Conclusion

Typeahead in Bootstrap is a powerful and user-friendly feature that enriches web applications with real-time search suggestions and autocompletion. Typeahead provides users with instant feedback as they type, helping them find relevant options quickly and efficiently. Bootstrap's Typeahead component is easy to implement and customizable, allowing developers to tailor the search functionality to their specific needs.

Typeahead is responsive, ensuring a seamless experience across various devices and screen sizes. By integrating Typeahead into web applications, developers can improve search functionality and enhance the user experience by offering an intuitive and time-saving way for users to find the information they need.