autocomplete/typeahead js plugin for bootstrap v5

Overview

bootstrap-5-autocomplete

This is a rewrite of https://github.com/Honatas/bootstrap-4-autocomplete for bootstrap v5.

Example

const ac = new Autocomplete(field, {
    data: [{label: "I'm a label", value: 42}],
    maximumItems: 5,
    onSelectItem: ({label, value}) => {
        console.log("user selected:", label, value);
    }
});

// later, when you need to change the dataset

ac.setData([
    {label: 'New York JFK', value: 'JFK'},
    {label: 'Moscow SVO', value: 'SVO'},
]);

Or use custom label/value keys:

const ac = new Autocomplete(field, {
    data: [{name: "entry1", text: "The first entry"}, {name: "entry2", text: "The second entry"}],
    label: "name",
    value: "text",
    onSelectItem: ({label, value}) => {
        console.log("user selected:", label, value);
    }
});

Or use a simple object instead of an array of objects:

const ac = new Autocomplete(field, {
    data: {entry1: "The first entry", entry2: "The second entry"},
    label: null,
    value: null,
    onSelectItem: ({label, value}) => {
        console.log("user selected:", label, value);
    }
});

Options

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

data:
The data from where autocomplete will lookup items to show. This data can be a simple object or an array of JSON objects. By default the format for every object in the array is as following, but you can also change the name of the label and value keys (see below):

{"label": "This is a text", "value": 42}

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

dropdownClass:
The class of the dropdown-menu element, which is the box that is displayed. Can take a string or an array of strings.

highlightClass:
The class to use when highlighting typed text on items. Only used when highlightTyped is true. Default is text-primary. Can take a string or an array of strings.

highlightTyped:
Whether to highlight (style) typed text on items. Default is true.

label:
The name of the label key in your data. The label is what will be shown on each item in the autocomplete list.

maximumItems:
How many items you want to show when the autocomplete is displayed. Default is 5. Set to 0 to display all available items.

onInput:
A callback function to execute on user input.

onSelectItem:
A callback that is fired every time an item is selected. It receives an object in following format:

{label: <label>, value: <value>}

showValue:
If set to true, will display the value of the entry after the label in the dropdown list.

showValueBeforeLabel:
If set to true and showValue also set to true, the value will be displayed before the label.

threshold:
The number of characters that need to be typed on the input in order to trigger the autocomplete. Default is 4.

value:
The name of the value key in your data.

License

MIT

Comments
  • onClick handling problem

    onClick handling problem

    Hi! Looks like problem exist with 'click' event handling.

    116        let dataLabel = e.target.getAttribute('data-label');
    117        let dataValue = e.target.getAttribute('data-value');
    

    Then you click on highlighted text in drop-down menu target has not button element but <span class=""text-primary"..> which does not have such attributes.

    I solved this issue for myself by using currentTarget

    116        let dataLabel = e.currentTarget.getAttribute('data-label');
    117        let dataValue = e.currentTarget.getAttribute('data-value');
    

    but im not sure if it best solution (cause i'm not js developer) :) So I don't make pool request.

    p/s also i add possibility to autocomplete more than one word (but it is 'duck' code, which replaces last entrance of 'lookup' variable, not whole input value - better solution to replace text before coursor position)

    opened by mrekin 4
  • Autocomplete & Ajax

    Autocomplete & Ajax

    Is there any better option to use JSON to recive data from other file ?

    const ac = new Autocomplete(field, { onInput: function () { dane=AJAX();ac.setData(dane);
    },data:[{label: "Text formatu JSON", value: 42}], .....

    opened by dugi07 3
  • set focus to first suggestion by down arrow key

    set focus to first suggestion by down arrow key

    Hi

    I think it would be nice to use the arrow keys to select a suggestion. This patch will set the focus to the first item in the dropdown when pressing the down arrow.

    Let me know what you think of such behavior

    Greetings CBke

    opened by CBke 3
  • how to setData with an array

    how to setData with an array

    hi team,

    can´t setData with a varible. get the error: auto5Error

    this is what my dataset is: auto5Data

    and this is what my function does: function gotData(arrayOfRows){

      listOfRCCs = [];
      arrayOfRows = JSON.parse(arrayOfRows);
    
      for (let i = 0; i < arrayOfRows.length; i++) {
          listOfRCCs.push( [{"label": arrayOfRows[i][6], "value": arrayOfRows[i][1]}]);
      };
    
      const list = document.getElementById('rccCat');
      const ac = new Autocomplete(list, {
          data: [listOfRCCs],
          maximumItems: 5,
          treshold: 2,
          onSelectItem: ({label, value}) => {
              console.log("user selected:", label, value);
          }
      });      
    
      console.log(ac);
    }
    

    any help would be very much appreciated!!!!! cheers tomek

    opened by hoptotomek 2
  • treshold -> threshold

    treshold -> threshold

    First off, amazing library!

    Just a small nitpick but I think the "treshold" option should be renamed to the lexically correct "threshold".

    opened by raiyansayeed 1
  • This does not work with accented characters such as ú

    This does not work with accented characters such as ú

    To get it to work for searchs with accented characters and accented items, you can add:

    const removeDiacritics = function(str) { return str .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') }

    and apply this in lines doing searches using indexOf such as

    const idx = removeDiacritics(item.label).toLowerCase().indexOf(removeDiacritics(lookup).toLowerCase());

    and

    if (removeDiacritics(item.label).toLowerCase().indexOf(removeDiacritics(lookup).toLowerCase()) >= 0) { items.appendChild(this.createItem(lookup, item)); if (this.options.maximumItems > 0 && ++count >= this.options.maximumItems) break; }

    opened by simon-stewart 1
  • Added the ability to set the label and value key names

    Added the ability to set the label and value key names

    You can now set the names of the label and value keys in the options. They default to label and value to not break the current behavior, but you can also set them to null, so that you can use a simple object instead of an array of objects, just like in bootstrap-4-autocomplete.

    Examples:

    const ac = new Autocomplete(field, {
        data: [{name: "entry1", text: "The first entry"}, {name: "entry2", text: "The second entry"}],
        label: "name",
        value: "text",
        onSelectItem: ({label, value}) => {
            console.log("user selected:", label, value);
        }
    });
    
    
    
    const ac = new Autocomplete(field, {
        data: {entry1: "The first entry", entry2: "The second entry"},
        label: null,
        value: null,
        onSelectItem: ({label, value}) => {
            console.log("user selected:", label, value);
        }
    });
    
    opened by sp00n 1
  • Fix bug: Navigation with cursor keys does not work

    Fix bug: Navigation with cursor keys does not work

    The navigation keys did not work in the dropdown with the following exception:

    bootstrap.esm.js?7b17:2393 Uncaught TypeError: Cannot read property '_selectMenuItem' of null
        at HTMLDivElement.dataApiKeydownHandler (bootstrap.esm.js?7b17:2393)
        at HTMLDocument.handler (bootstrap.esm.js?7b17:460)
    

    The reason is that the data-toggle-field changed from data-toggle to data-bs-toggle in bootstrap 5.

    opened by lukasjelonek 1
  • render again if data has changed

    render again if data has changed

    Hi

    If the data changed, the autocomplete should be rendered again. So the matches will look in the new provided data and display accordingly.

    Greetings CBke

    opened by CBke 1
  • onSelectItem not returning value only returns label

    onSelectItem not returning value only returns label

    There is an error in line 99 that cause not returning value when onSelectItem.

    The code in line 99 "value: e.target.value" must be "value: e.target.dataset.value".

    opened by opennexo 1
  • Label Double quotes issue

    Label Double quotes issue

    When choosing the value, I am using onSelectItem to apply the value to a hidden field. The problem is that the label has a double quote in it and it breaks the HTML by chunking the label.

    How can I escape the label value before it is applied to the input?

    opened by Binternet 0
  • import error

    import error

    I am having a "Uncaught SyntaxError: Cannot use import statement outside a module (at autocomplete.js:1:1)" error.

    When I include type="module" to the script tag, then I get an "Uncaught ReferenceError: Autocomplete is not defined" error

    opened by subliminalhash 3
  • How to refresh the autocomplete data?

    How to refresh the autocomplete data?

    Hi, Is there a way to refresh the autocomplete options once the list is loaded. For example, I am using a dropdown next to the search bar. Based on the selection in the dropdown, the results in the autocomplete should get filtered. However, if I fire the Autocomplete event every time a value is selected, it creates a new dropdown list based on the different datasource. Any suggestions to refresh or destroy the existing autocomplete dropdown to repopulate with freshdata?

    opened by anantc88 2
  • Bootstrap 5 Autocomplete not working when using it inside input group with another dropdown

    Bootstrap 5 Autocomplete not working when using it inside input group with another dropdown

    I use the following code:

    <div class="input-group">
      <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown"></button>
      <ul class="dropdown-menu">
        <li><button class="dropdown-item" type="button" value="1">1</button>
        <li><button class="dropdown-item" type="button" value="2">2</button>
        <li><button class="dropdown-item" type="button" value="3">3</button>
      </ul>
      <input class="form-control" name="s" id="autocomplete" type="text" placeholder="Search" autofocus>
    </div>
    

    But it's not working, because there is another dropdown next to the autocomplete inside the input group, so instead of showing the autocomplete dropdown on typing, the other dropdown will be shown.

    Is there a way to fix this problem? Thank you very much!

    opened by AgentSmith0 0
  • Bootstrap 5 Autocomplete returns null onSelectItem

    Bootstrap 5 Autocomplete returns null onSelectItem

    Hi. How are you. Nice code but sometimes it returns null my code:

    async function getProductsArray() {
    
      let autoCompleteArray = [];
    
      try {
    
        const [productsArray, productsDefault] = await getSettingsProducts();
        productsArray.sort();
        productsArray.forEach((element, index) => {
          autoCompleteArray.push({
            label: element,
            value: element
          });
    
        });
      
        const field = document.getElementById('productsAutoComplete');
        const ac = new Autocomplete(field, {
            //data: [{label: "I'm a label", value: 42}],
            data: autoCompleteArray,
            maximumItems: 5,
            threshold: 1,
            onSelectItem: ({
                label,
                value
            }) => {
                console.log("user selected:", label, value);//<--------sometimes null null
                document.getElementById('productsAutoComplete').value = "";
            inputVal(label);
            }
        });
    
      } catch (error) {
        console.log("Get Products Error: ", error);
        // errorInfo(error)
      }
    }
    

    It looks like it works, but not always. Sometimes "onSelectItem" returns "null"(about 25%). Even if the same element is clicked. I checked on chrome and Firefox. On Chrome, a bit better.

    opened by awariat 2
Owner
Evgeny Zinoviev
Evgeny Zinoviev
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Extends Bootstrap Tooltips and Popovers by adding custom classes. Available for Bootstrap 3 and Bootstrap 4.

Bootstrap Tooltip Custom Class Extends Bootstrap Tooltips and Popovers by adding custom classes. Available for Bootstrap 3 and Bootstrap 4. Define you

Andrei Victor Bulearca 14 Feb 10, 2022
A simple Form Validation Utility for Bootstrap 3, Bootstrap 4, and Bootstrap 5 for Humans.

bootstrap-validate A simple Form Validation Utility for Bootstrap 3, Bootstrap 4, and Bootstrap 5 for Humans. ?? Support us with Developer Merchandise

null 138 Jan 2, 2023
Bootstrap Colorpicker is a modular color picker plugin for Bootstrap.

Bootstrap Colorpicker Bootstrap Colorpicker is a modular color picker plugin for Bootstrap 4. THIS PROJECT IS NOT MAINTAINED ANYMORE. After almost 10

Javi Aguilar 1.4k Dec 22, 2022
Obsidian plugin that adds autocomplete and auto-formatting to frontmatter tags.

Obsidian Front Matter Tag Wizard Tired of having to type # to get tag autocompletion in your Obsidian note front matter? I feel your pain. This plugin

Eric 10 Nov 5, 2022
jQuery plugin for fuzzy search in autocomplete

fuzzycomplete jQuery plugin for fuzzy search in an autocomplete form, which uses Fuse.js. By harnessing the flexibility Fuse.js, this plugin allows yo

null 14 Nov 1, 2021
Autocomplete für YForm Tabellen

?? WIP REDAXO-Addon: YForm Autocomplete Dieses Addon ermöglicht, Felder einer YForm-Tabelle über eine weitere automatisiert zu befüllen. Features Todo

Thorben 2 Jun 17, 2022
Autocomplete for HTMLTextAreaElement and more.

Textcomplete Autocomplete for HTMLTextAreaElement and more. Document. Packages Textcomplete consists of subpackages: Name Description @textcomplete/co

Yuku Takahashi 1.7k Dec 28, 2022
Autocomplete, diagnostics, hover info & more for the Wally package manager

Wally Utilities This VSCode extension provides some nice-to-haves when using the Wally package manager. The extension can be downloaded from the Visua

Filip Tibell 4 Jul 28, 2022
Email Genie Allows autocomplete on email field by providing a list of domain suggestions (gmail.com, outlook.com, etc.).

Allows users to easily and quickly complete an email field by providing a list of domain suggestions (gmail.com, outlook.com, etc.). This package stands out for its flexibility, its compatibility with libraries / frameworks, but especially its use of basic HTML and Javascript functionalities that maximize the native behavior of desktop AND mobile browsers.

Simon Arnold 3 Oct 4, 2022
An autocomplete component, built to be accessible.

Accessible autocomplete The accessible autocomplete is a component that helps users choose answers from a list you provide. You can also use it to mak

Government Digital Service 771 Jan 4, 2023
Autocomplete component created with pure javascript

Pickle Complete Pickle complate is a autocomplate component written as completely pure javascript. Just send json object or request information have f

Kadir Barış Bozat 2 Jul 5, 2022
Bootstrap plugin for markdown editing

Bootstrap Markdown Markdown editing meets Bootstrap. Demo and documentation available at http://toopay.github.io/bootstrap-markdown/ Compatibility Ver

Refactory 2k Dec 27, 2022
jQuery tags input plugin based on Twitter Bootstrap.

Bootstrap Tags Input Bootstrap Tags Input is a jQuery plugin providing a Twitter Bootstrap user interface for managing tags. Current stable version: v

null 26 Dec 21, 2022
The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with Bootstrap 5 support.

bootstrap-select The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with

SnapAppointments 9.7k Dec 30, 2022
A Bootstrap plugin to create input spinner elements for number input

bootstrap-input-spinner A Bootstrap / jQuery plugin to create input spinner elements for number input. Demo page with examples Examples with floating-

Stefan Haack 220 Nov 7, 2022
The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with Bootstrap 5 support

bootstrap-select The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with

SnapAppointments 9.7k Dec 30, 2022
A jQuery plugin wrapper around Bootstrap Alerts, to create Notifications (Toasts)

bootstrap-show-notification A jQuery plugin wrapper around Bootstrap 4 Alerts, to show them as toasts (also called notifications) dynamically from Jav

Stefan Haack 10 Aug 22, 2022