Powerful Autocomplete With Asynchronous Data Fetch – autocomplete.js

Category: Form , Javascript | November 19, 2021
Author:tomik23
Views Total:42 views
Official Page:Go to website
Last Update:November 19, 2021
License:MIT

Preview:

Powerful Autocomplete With Asynchronous Data Fetch – autocomplete.js

Description:

A feature-rich, highly-customizable, fully accessible autocomplete library written in Vanilla JavaScript.

Features:

  • Supports both Single and Multiple select.
  • Supports for Asynchronous Data Fetching.
  • Allows you to group results.
  • Allows you to add checkboxes to the beginning of the results.

How to use it:

1. Download and import the autocomplete.css & autocomplete.min.js into the document.

<link rel="stylesheet" href="/path/to/autocomplete.css" />
<script src="/path/to/autocomplete.min.js"></script>

2. Load the polyfills for users who are still using the legacy browsers.

if (!('Promise' in window)) {
  var script = document.createElement('script');
  script.src =
    'https://polyfill.io/v3/polyfill.min.js?features=Promise%2CElement.prototype.closest';
  document.getElementsByTagName('head')[0].appendChild(script);
}

3. Initialize the autocomplete.js on the target input field and fetch data from an external data source as follows:

<input type="text" id="example" placeholder="Type Something" />
new Autocomplete('example', {
    onSearch: ({ currentValue }) => {
      const api = `/path/to/datasource/`;
      return new Promise((resolve) => {
        fetch(api)
          .then((response) => response.json())
          .then((data) => {
            resolve(data);
          })
          .catch((error) => {
            console.error(error);
          });
      });
    },
    onResults: ({ matches }) => {
      return matches
        .map(el => {
          return `
            <li>${el.name}</li>`;
        }).join('');
    }
});

4. The library also supports local data.

new Autocomplete('local', {
    onSearch: ({ currentValue }) => {
      const data = [
        { "name": "JavaScript" },
        { "name": "CSS" },
        { "name": "HTML" },
        { "name": "Python" }
      ];
      return data.sort((a, b) => a.name.localeCompare(b.name))
        .filter(element => {
          return element.name.match(new RegExp(currentValue, 'i'))
        })
    },
    onResults: ({ matches }) => {
      return matches
        .map(el => {
          return `
            <li>${el.name}</li>`;
        }).join('');
    }
});

5. Possible options and functions.

new Autocomplete('example', {

    // search delay
    delay: 500,

    // shows clear button
    clearButton: true,

    // auto select the first result
    selectFirst: false,

    // adds text to the input field as you move through the results with the up/down cursors
    insertToInput: false,

    // the number of characters entered to trigger the search
    howManyCharacters: 1,

    // name of the class by which you will name the group element
    classGroup: 'group-by',

    // disable close on select
    disableCloseOnSelect: false,

    //  toggle showing all values when the input is clicked, like a default dropdown
    showAllValues: false,

    // prevents results from hiding after clicking on element with this class
    classPreventClosing: ``,

    // determine whether to cache characters entered in the input field
    cache: false,

    onResults = () => { },
    onSearch = () => { },
    onSubmit = () => { },
    onOpened = () => { },
    onReset = () => { },
    onRender = () => { },
    noResults = () => { },
    onSelectedItem = () => { },

});

Changelog:

v1.7.0 (11/19/2021)

  • fixed examples

v1.6.9 (11/15/2021)

  • fixed results do not scroll to the top

v1.6.8 (11/13/2021)

  • global output folder dist, includes iife, umd and esm compressed and uncompressed files

v1.6.6 (11/07/2021)

  • Added unminified javascript file

v1.6.5 (11/04/2021)

  • Fixed typo in clear label
  • Added a new parameter that allows you to insert your own aria-label for the ‘x’ button to clear data in the input field.

v1.6.4 (11/04/2021)

  • Fixed: Reset margin on autocomplete ul

v1.6.3 (09/26/2021)

  • documentation improvements

v1.6.1 (09/13/2021)

  • Fixed: Calback function ‘onSearch’

v1.6.0 (09/04/2021)

  • Added showAllValues, this option will toggle showing all values when the input is clicked, like a default dropdown
  • ‘rollup.config.js’ to remove forgotten console.log and debugger
  • Rebuilding html with examples so you don’t have to add js code to html manually. From now on, the code is dynamically downloaded from js as text and inserted into the appropriate place, and then presented by ‘prism’
  • Bugs fixed

v1.5.0 (08/31/2021)

  • Added onRender – callback function when we want to add additional elements, e.g. some buttons, links or plain text
  • Added classPreventClosing – Prevents results from hiding after clicking on element with this class
  • Added Footer/Header – new example, showing how to add an element above the results and below
  • wrap the results of additional divs. Useful when we want to add additional elements to the results, e.g. a legend, links, buttons, etc
  • fixed: following a record when navigating records up/down with arrows and when using classGroup

v1.1.4 (08/14/2021)

  • fix: clearButton

v1.1.2 (08/14/2021)

  • added new example

v1.1.0 (08/11/2021)

  • feat: New param cache

v1.0.44 (06/30/2021)

  • chore: removing unused plugin ‘rollup-plugin-postcss’

You Might Be Interested In:


Leave a Reply