bootstrap autocomplete

Bootstrap 4 autocomplete dropdown

Rate this article

Share this article

Read bootstrap 4 autocomplete dropdown for more information.

 

bootstrap autocomplete

Features
  • Fast.
  • Easy. No complex configuration. HTML attributes supported.
  • Modals supported. No problems in modals.
  • Customizable. You can customize every single step in the suggesting workflow.
  • Batteries included. It works out of the box for Bootstrap v3 and v4.
  • i18n. Use data-* attributes to specify the strings to use in case of errors/noresults.
  • Styles. No custom styles. Uses standard Bootstrap’s dropdown.

bootstrap 4 autocomplete dropdown

Build a search with autocomplete without any coding

Getting Started

Bootstrap Autocomplete works as a plugin. Add it to your page

<script src="bootstrap-autocomplete.min.js"></script>

Using CDN (thanks to JSDelivr)

STABLE version 2.3.0
<script src="https://cdn.jsdelivr.net/gh/xcash/bootstrap-autocomplete@v2.3.0/dist/latest/bootstrap-autocomplete.min.js"></script>
Latest version (this is the development branch)
<script src="https://cdn.jsdelivr.net/gh/xcash/bootstrap-autocomplete@master/dist/latest/bootstrap-autocomplete.min.js"></script>

That’s it! Go on to enhance your text fields! 🙂

Basic usage
Text Autocomplete

Autocomplete is not enabled by default. You must activate it in the fields you want to enhance. Of course, you can also use a wide selector to enable it on specific classes or tags.

Suppose you have a field as follows

<input class="form-control basicAutoComplete" type="text" autocomplete="off">

Here the class basicAutoComplete is used to identify all the fields on which to activate a basic autocomplete. Then in Javascript we activate it.

$('.basicAutoComplete').autoComplete({
    resolverSettings: {
        url: 'testdata/test-list.json'
    }
});

In this example, we specified the URL to use. Autocomplete will automatically make an Ajax GET request to that URL using an argument named q with the text typed by the user. Rate limits are enforced and the minimum field length is 2.

Even simpler you can pass the URL directly in the markup

<input class="form-control basicAutoComplete" type="text"
        data-url="myurl"
        autocomplete="off">

and enhance it just with

$('.basicAutoComplete').autoComplete();
Response Format

We know how to start an autocomplete lookup but what about the results?

The default configuration expects a simple list in JSON format. Like

[
    "Google Cloud Platform",
    "Amazon AWS",
    "Docker",
    "Digital Ocean"
]
Select Autocomplete

One of the main features of Bootstrap Autocomplete is to enhance <select> fields as easy as <input> text fields. Selects are useful to restrict choices to a set of possibilities.

Enhancing a select is no different than text fields.

<select class="form-control basicAutoSelect" name="simple_select"
    placeholder="type to search..."
    data-url="testdata/test-select-simple.json" autocomplete="off"></select>
$('.basicAutoSelect').autoComplete();

Nice! 🙂

Response Format for Select

In this case, we need two values in the response: id and a text.

[
    { "value": 1, "text": "Google Cloud Platform" },
    { "value": 2, "text": "Amazon AWS" },
    { "value": 3, "text": "Docker" },
    { "value": 4, "text": "Digital Ocean" }
]

Add Search to your  Website

Events

Bootstrap Autocomplete triggers usual events.
change – Value changed

And custom.

autocomplete.select – (evt, item) The element item is the item selected by the user and currently selected in the field.

autocomplete.freevalue – (evt, value) The text field contains value as the custom value (i.e. not selected from the choices dropdown).

Reference
Activating Autocomplete
$(…).autoComplete([options])
Enhance the form fields identified by the selector

Arguments:

  • options – Configuration options of type ConfigOptions.

Configuration options

formatResult
callback(item)
Arguments:

  • item (object) – The item selected or rendered in the dropdown.

Returns:

An object { id: myItemId, text: myfancyText, html?: myfancierHtml }.

minLength
Default: 3. Minimum character length to start lookup.
autoSelect
Default: true. Automatically selects selected item on blur event (i.e. using TAB to switch to next field).
resolver
Default: ajax. Resolver type. custom to implement your resolver using events.
noResultsText
Default: No results. Text to show when no results found.
resolverSettings
Object to specify parameters used by default resolver.

url
Url used by default resolver to perform lookup query.
requestThrottling
Default: 500. Time to wait in ms before starting a remote request.
events
Object to specify custom event callbacks.

func(qry, callback, origJQElement)
Function called to perform a lookup.

Arguments:

  • qry (string) – Query string.
  • callback – Callback function to process results. Called passing the list of results callback(results).
  • origJQElement (JQuery) – Original jQuery element.
searchPost
func(resultsFromServer, origJQElement)
Function called to manipulate server response. Bootstrap Autocomplete needs a list of items. Use this function to convert any server response in a list of items without reimplementing the default AJAX server lookup.

Arguments:

  • resultsFromServer – Result received from the server. Using the default resolver this is an object.
  • origJQElement (JQuery) – Original jQuery element.

Returns:

List of items.

Following events are available to fine tune every lookup aspect. Rarely used in common scenarios

typed
func(newValue, origJQElement)
Field value changed. Use this function to change the searched value (like prefixing it with some string, filter some characters, …). Or to stop lookup for certain values.Arguments:

  • newValue (string) – New value.
  • origJQElement (JQuery) – Original jQuery element.

Returns:

(Un)modified value or false to stop the execution.

searchPre
func(newValue, origJQElement)
Before starting the search. Like in the typed event, this function can change the search value. The difference is this event is called after minLength checks.Arguments:

  • newValue (string) – New value.
  • origJQElement (JQuery) – Original jQuery element.

Returns:

(Un)modified value or false to stop the execution.

As a reference the lookup workflow calls events in the following order:

typed -> searchPre -> search -> searchPost
Advanced usage
Set custom value

To set an initial or change the value of the field.

$('.myAutoSelect').autoComplete('set', { value: myValue, text: myText });

Customize results using default AJAX resolver

Using the searchPost the event you can manipulate the result set making it compatible with autocomplete default. This is useful to bypass the customization of the entire search AJAX call.

$('.myAutoSelect').autoComplete({
    events: {
        searchPost: function (resultFromServer) {
            return resultFromServer.results;
        }
    }
});
Translating messages

To customize “no results” message use the following markup.

<select class="form-control emptyAutoSelect" name="empty_select"
    data-url="testdata/test-empty.json"
data-noresults-text="Nothing to see here."    autocomplete="off"></select>

Add Search to your  Website

FAQs

How to Create Autocomplete on an Input Field?

The autocomplete property defines whether or not autocomplete should be turned on for an input field. You can create Autocomplete by following these steps: 

  1. Create a JavaScript array by adding HTML.
  2. Boost CSS
  3. Insert JavaScript
  4. On “myInput,” start the autocomplete effect.

How to Create Typeahead in Bootstrap 5?

Simply follow these steps:

  1. Launch your Bootstrap 5 project and load the primary JavaScript autocomplete.js file.
  2. Create a list of recommendations to be used in the autocomplete list.
  3. The autocomplete list should now be attached to your input field.
  4. Specify how much is the most items that can be shown. The default is 5.
  5. Establish the minimum character count required to display the autocomplete list. The default is 2.
  6. Change the highlighted characters’ font styles.
  7. Obtain the chosen object.
  8. Change the labels for the ‘Label’ and ‘Value’ keys.
  9. Choose whether to show the value of the entry in the dropdown list that comes after the label. The default is false.
  10. Decide if the value of the element that comes before the label in the dropdown list should be shown. Default is false.

How to Turn Off Form Autocompletion?

Use the autocomplete attribute of the input and form components to turn off text autocomplete in forms. The ‘off’ value of this attribute is what you require.

This may be carried out in a ‘form’ for an entire form or for particular ‘input’ elements:

  • To turn off autocomplete for the full form, add autocomplete= ‘off’ to the form> element.
  • For a particular form’s input> element, add autocomplete= ‘off’.

How to Disable the Browser Autocomplete and Autofill?

Follow these steps to disable your browser autocomplete and autofill:

  • Press the menu button. (Screen top right, three dots)
  • Select ‘Settings’
  • Expand the region for which you want to turn off Autofill in the “Autofill” section
  • If the setting is on, turn it off. Your settings will be automatically saved by the system

How to Make Auto Complete Result in Vue Bootstrap?

  • Your template will require at least two of these items in order to develop an autocomplete component: an input and a list.
  • To determine when to display such findings, your programmes must monitor input changes.
  • You must add an event listener for @input in order to filter the results since you need to know when the user has done typing.
  • Modify App.vue by opening it and adding the autocomplete component as an import and reference.
  • Go back to SearchAutocomplete.vue in your code editor and add the necessary code to filter and display the search results.
  • Additionally, make sure that the list of results is only displayed once the user has entered anything. By using v-show to conditionally display it, you may achieve that.
  • Users should be able to select a result by clicking on it, and the selected value should then be shown automatically. You may do this by setting the value of the click event as the search phrase and listening for the click event.
  • You must pay attention to a click event outside of this component to close the results list after the user clicks off the results list.

How to turn off form autocompletion

To switch off structure autocompletion, you can utilize the “autocomplete” property in your HTML code. The procedure is as follows:

Open the HTML file that contains the form for which you want to disable autocomplete.

Add the “autocomplete” attribute to the form and set its value to “off” for each input field.

To see the changes, save the HTML file and reload your website.

Keep in mind that the “autocomplete” attribute may be disabled or overridden by some browsers. In these situations, you can disable autocomplete for the form fields with JavaScript.

How to use autocomplete in Bootstrap?

To use autocomplete in Bootstrap, follow these steps:

Your HTML code should contain the Bootstrap files that are required. You can link to the Bootstrap CDN or download the Bootstrap files and link to them locally.

Add an information field to your HTML code, alongside a compartment to show the autocomplete results

Introduce the autocomplete module utilizing JavaScript

Modify the appearance and conduct of the autocomplete module to meet your requirements. You can adjust the delay between keystrokes and autocomplete suggestions, change the style of the results, and more.

 

Are you showing the right products, to the right shoppers, at the right time? Contact us to know more.
You may also like