Smart Autocomplete Component For Bootstrap 5/4

File Size: 77.7 KB
Views Total: 7491
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Smart Autocomplete Component For Bootstrap 5/4

A lightweight and easy-to-use autocomplete component for Bootstrap 5 and Bootstrap 4 frameworks. It was written in ES 6 and is100% compliant with Twitter Bootstrap markup, styles, and API.

See Also:

How to use it:

1. Load the necessary Bootstrap framework in the document.

<!-- Required For Bootstrap 4 -->
<script src="/path/to/cdn/jquery.slim.min.js"></script>

<!-- Bootstrap 5 or 4 Framework -->
<link rel="stylesheet" href="/path/to/cdn/bootstrap.min.css" />
<script src="/path/to/cdn/bootstrap.bundle.min.js"></script>

2. Import the autocomplete component.

import Autocomplete from "./autocomplete.min.js";

3. Initialize the plugin on the target input field and specify an array of suggestions for the autocomplete list.

<input type="text" class="form-control autocomplete" id="autocompleteInput" placeholder="Type something" />
Autocomplete.init("input.autocomplete", {
  items: [
    {
      id: 'opt1',
      label: 'Option 1',
      value: 'opt1',
      title: 'Option 1',
      data: {
        key: 1
      },
    },
    {
      id: 'opt2',
      label: 'Option 2',
      value: 'opt1',
      title: 'Option 2',
      data: {
        key: 2
      },
    }
  ],
  valueField: "id",
  labelField: "title",
});
// It also supports groups
[
  {
    group: "My Group Name",
    items: [
      {
        value: "...",
        label: "...",
      },
    ],
  },
];

4. It also works with the datalist.

<input type="text" class="form-control" id="autocompleteDatalist" data-datalist="list-timezone" placeholder="Type something" />
<datalist id="list-timezone">
  <option value="asia_aden">Asia/Aden</option>
  <option>Asia/Aqtau</option>
  <option>Asia/Baghdad</option>
  <option>Asia/Barnaul</option>
  <option>Asia/Chita</option>
  <option>Asia/Dhaka</option>
  <option>Asia/Famagusta</option>
  <option>Asia/Hong_Kong</option>
  <option>Asia/Jayapura</option>
  <option>Asia/Kuala_Lumpur</option>
  <option>Asia/Jakarta</option>
</datalist>
new Autocomplete(document.getElementById("autocompleteDatalist"), {
    // options
});

5. Or load options from a remote data source.

<input type="text" class="form-control" id="autocompleteRemote" data-server="demo.json" placeholder="Type something" />

<!-- OR -->
<input type="text" class="form-control" id="autocompleteRemote" 
       data-server="/path/to/data/"
       data-live-server="true" 
       data-value-field="id"
       data-label-field="name"
       data-server-params='{"related":"related_field"}' 
       placeholder="Type something" />
new Autocomplete(document.getElementById("autocompleteRemote"), {
    // options
});

6. Available options.

  • showAllSuggestions: Show all suggestions even if they don't match
  • suggestionsThreshold: Number of chars required to show suggestions
  • maximumItems: Maximum number of items to display
  • autoselectFirst: Always select the first item
  • ignoreEnter: Ignore enter if no items are selected
  • updateOnSelect: Update input value on selection
  • highlightTyped: Highlight matched part of the label
  • highlightClass: Class added to the mark label
  • fullWidth: Match the width on the input field
  • fixed: Use fixed positioning
  • fuzz: Enable fuzz search
  • fillIn: Show fill in icon.
  • startsWith: Must start with the string
  • preventBrowserAutocomplete: Prevent the native browser autocomplete
  • itemClass: Applied to the dropdown item
  • fullWidth: Match the width on the input field
  • labelField: Key for the label
  • valueField: Key for the value
  • queryField: Key for the query parameter for server
  • searchFields:  Array Key for the search
  • items: An array of label/value objects or an object with key/values
  • hiddenInput: Create an hidden input which stores the valueField
  • hiddenValue: Populate the initial hidden value. Mostly useful with liveServer
  • clearControl: Selector that will clear the input on click
  • datalist: The id of the source datalist
  • source: A function that provides the list of items
  • server: Endpoint for data provider
  • serverParams: Parameters to pass along to the server
  • fetchOptions: Any other fetch options (https://developer.mozilla.org/en-US/docs/Web/API/fetch#syntax)
  • liveServer: Should the endpoint be called each time on input
  • noCache: Prevent caching by appending a timestamp
  • debounceTime: Debounce time for live server
  • notFoundMessage: Display a no suggestions found message. Leave empty to disable
new Autocomplete(document.getElementById("autocompleteRemote"), {
    showAllSuggestions: false,
    suggestionsThreshold: 2,
    maximumItems: 0,
    autoselectFirst: true,
    ignoreEnter: false,
    tabSelect: true,
    updateOnSelect: false,
    highlightTyped: false,
    highlightClass: '',
    fullWidth: false,
    fixed: false,
    fuzzy: false,
    fillIn: false,
    startsWith: false,
    fillIn: true,
    preventBrowserAutocomplete: true,
    itemClass: "",
    activeClasses: ["bg-primary", "text-white"],
    labelField: "label",
    valueField: "value",
    searchFields: ["label"],
    queryParam: "query",
    items: [],
    source: null,
    hiddenInput: false,
    hiddenValue: "",
    clearControl: "",
    datalist: "",
    server: "",
    serverMethod: "GET",
    serverParams: {},
    serverDataKey: "data",
    fetchOptions: {},
    liveServer: false,
    noCache: true,
    debounceTime: 300,
    notFoundMessage: "",
});

7. Callback functions.

new Autocomplete(document.getElementById("autocompleteRemote"), {

    // Callback function that returns the label
    onRenderItem: (item, label, inst) => {
      return label;
    },

    // Callback function to call on selection
    onSelectItem: (item, inst) => {},

    // Callback function to process server response
    onServerResponse: (response, inst) => {
      return response.json();
    },

    onServerError: (e, signal, inst) => {
      // Current version of Firefox rejects the promise with a DOMException
      if (e.name === "AbortError" || signal.aborted) {
        return;
      }
      console.error(e);
    },

    // Callback function to call on change-event. Returns currently selected item if any
    onChange: (item, inst) => {},

    // Callback function before fetch
    onBeforeFetch: (inst) => {},

    // Callback function after fetch
    onAfterFetch: (inst) => {},
    
});

Changelog:

v1.1.33 (2024-10-16)

  • Fix active classes not being set properly

v1.1.32 (2024-10-08)

  • Keep natural order when using numerical indexes

v1.1.31 (2024-09-13)

  • Added tabSelect config

v1.1.29 (2024-08-19)

  • Fix clicking on scroll in a modal

v1.1.28 (2024-07-03)

  • don't select the option with the mouse unless you are actually using it

v1.1.27 (2024-06-19)

  • fix blur + clicking on scroll in a modal

v1.1.26 (2024-04-16)

  • Add onServerError callback

v1.1.25 (2023-12-01)

  • New fillIn feature

v1.1.24 (2023-11-29)

  • Support nested data key

v1.1.23 (2023-10-28)

  • Fix highlight for labels which does not contains lookup

v1.1.21 (2023-09-14)

  • Move class to dropdown item

v1.1.20 (2023-07-24)

  • Added itemClass option
  • Added preventBrowserAutocomplete option

v1.1.19 (2023-07-20)

  • Switch back to autocomplete=off
  • Tweak ignoreEnter so that it can still add values if something is selected

v1.1.17 (2023-07-18)

  • Add startsWith option

v1.1.16 (2023-07-03)

  • Prevent handleEvent to be rebound
  • Add dynamic params

v1.1.15 (2023-07-01)

  • add option for change-event

v1.1.14 (2023-06-13)

  • Fix firefox accessibility attributes

v1.1.13 (2023-06-09)

  • Add groups

v1.1.11 (2023-06-08)

  • Add search fields

v1.1.10 (2023-06-08)

  • Add serverDataKey param
  • Fixed issue with numbers as keys
  • Also use name for related param

v1.1.9 (2023-05-17)

  • Update

v1.1.8 (2023-05-15)

  • Fix some edge case with labels

v1.1.7 (2023-05-11)

  • Improve hidden input default value (can be found automatically or set using hidden-value)

v1.1.6 (2023-05-09)

  • Support hidden input value

v1.1.5 (2023-04-22)

  • Update autocomplete.js
  • Improve callbacks (pass instance)

v1.1.4 (2023-03-07)

  • Add fetch options

v1.1.3 (2023-03-02)

  • Improve scroll handling in menu
  • RTL support improved
  • Positioning improved
  • Fix arrow down not showing the menu

v1.1.2 (2023-03-01)

  • fix message not found not being displayed
  • configurable active classes

v1.1.1 (2023-01-16)

  • Add fixed positioning

v1.1 (2023-01-13)

  • Improve positioning in multiple scenarios
  • Renamed queryField to queryParam to be more consistent

v1.0.4 (2023-01-02)

  • Add queryField param

v1.0.3 (2022-11-22)

  • Minor tweaks

v1.0.2 (2022-11-14)

  • Add source option
  • Fix setData for server

 


This awesome jQuery plugin is developed by lekoala. For more Advanced Usages, please check the demo page or visit the official website.