https://github.com/lekoala/bootstrap5-autocomplete
Autocomplete for Bootstrap 5 (and 4!)
https://github.com/lekoala/bootstrap5-autocomplete
autocomplete bootstrap bootstrap5 es6
Last synced: 6 months ago
JSON representation
Autocomplete for Bootstrap 5 (and 4!)
- Host: GitHub
- URL: https://github.com/lekoala/bootstrap5-autocomplete
- Owner: lekoala
- License: mit
- Created: 2022-11-03T14:55:26.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2025-03-12T09:08:01.000Z (8 months ago)
- Last Synced: 2025-03-31T20:05:17.498Z (7 months ago)
- Topics: autocomplete, bootstrap, bootstrap5, es6
- Language: JavaScript
- Homepage:
- Size: 502 KB
- Stars: 96
- Watchers: 6
- Forks: 21
- Open Issues: 2
-
Metadata Files:
- Readme: readme.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
- jimsghstars - lekoala/bootstrap5-autocomplete - Autocomplete for Bootstrap 5 (and 4!) (JavaScript)
README
# Autocomplete for Bootstrap 4/5
[](https://www.npmjs.com/package/bootstrap5-autocomplete)
[](https://www.npmjs.com/package/bootstrap5-autocomplete)
## How to use
An ES6 autocomplete for your `input` using standards Bootstrap 5 (and 4) styles.
No additional CSS needed!
```js
import Autocomplete from "./autocomplete.js";
Autocomplete.init();
```
When using NPM package:
```js
import Autocomplete from "bootstrap5-autocomplete";
Autocomplete.init();
```
When using CDN version from TypeScript file, for example:
```ts
import Autocomplete, { type Config } from "https://cdn.jsdelivr.net/gh/lekoala/bootstrap5-autocomplete@master/autocomplete.js";
const options: Partial = {
//...
}
Autocomplete.init('#myInput', options);
```
Path mapping in `tsconfig.json` is required in order to load types from local NPM package:
```json
{
"compilerOptions": {
//...
"paths": {
"https://cdn.jsdelivr.net/gh/lekoala/bootstrap5-autocomplete@master/autocomplete.js": [ "./node_modules/bootstrap5-autocomplete" ]
}
}
}
```
## Server side support
You can also use options provided by the server. This script expects a JSON response with the following structure:
```json
{
"optionValue1":"optionLabel1",
"optionValue2":"optionLabel2",
...
}
```
or
```json
[
{
"value": "server1",
"label": "Server 1"
},
...
]
```
Simply set `data-server` where your endpoint is located. The suggestions will be populated upon init except if `data-live-server` is set, in which case, it will be populated on type. A ?query= parameter is passed along with the current value of the searchInput.
Data can be nested in the response under the data key (configurable with serverDataKey).
## Options
Options can be either passed to the constructor (eg: optionName) or in data-option-name format.
| Name | Type | Description |
|----------------------------|------------------------------------------------|---------------------------------------------------------------------------------------------------------|
| showAllSuggestions | Boolean | Show all suggestions even if they don't match |
| suggestionsThreshold | Number | Number of chars required to show suggestions |
| maximumItems | Number | Maximum number of items to display |
| autoselectFirst | Boolean | Always select the first item |
| ignoreEnter | Boolean | Ignore enter if no items are selected (play nicely with autoselectFirst=0) |
| tabSelect | Boolean | Tab will trigger selection if active |
| updateOnSelect | Boolean | Update input value on selection (doesn't play nice with autoselectFirst) |
| highlightTyped | Boolean | Highlight matched part of the label |
| highlightClass | String | Class added to the mark label |
| fullWidth | Boolean | Match the width on the input field |
| fixed | Boolean | Use fixed positioning (solve overflow or complex layout issues) |
| fuzzy | Boolean | Fuzzy search |
| startsWith | Boolean | Must start with the string. Defaults to false (it matches any position). |
| fillIn | Boolean | Show fill in icon. |
| preventBrowserAutocomplete | Boolean | Additional measures to prevent browser autocomplete |
| itemClass | String | Applied to the dropdown item. Accepts space separated classes. |
| activeClasses | Array | By default: ["bg-primary", "text-white"] |
| labelField | String | Key for the label |
| valueField | String | Key for the value |
| searchFields | Array | Key for the search |
| queryParam | String | Key for the query parameter for server |
| items | Array \| Object | An array of label/value objects or an object with key/values |
| source | function | A function that provides the list of items |
| hiddenInput | Boolean | Create an hidden input which stores the valueField |
| hiddenValue | String | Populate the initial hidden value. Mostly useful with liveServer. |
| clearControl | String | Selector that will clear the input on click. |
| datalist | String | The id of the source datalist |
| server | String | Endpoint for data provider |
| serverMethod | String | HTTP request method for data provider, default is GET |
| serverParams | String \| Object | Parameters to pass along to the server. You can specify a "related" key with the id of a related field. |
| serverDataKey | String | By default: data |
| fetchOptions | Object | Any other fetch options (https://developer.mozilla.org/en-US/docs/Web/API/fetch#syntax) |
| liveServer | Boolean | Should the endpoint be called each time on input |
| noCache | Boolean | Prevent caching by appending a timestamp |
| debounceTime | Number | Debounce time for live server |
| notFoundMessage | String | Display a no suggestions found message. Leave empty to disable |
| onRenderItem | [RenderCallback](#RenderCallback) | Callback function that returns the label |
| onSelectItem | [ItemCallback](#ItemCallback) | Callback function to call on selection |
| onClearItem | [ValueCallback](#ValueCallback) | Callback function to call on clear |
| onServerResponse | [ServerCallback](#ServerCallback) | Callback function to process server response. Must return a Promise |
| onServerError | [ErrorCallback](#ErrorCallback) | Callback function to process server errors. |
| onChange | [ItemCallback](#ItemCallback) | Callback function to call on change-event. Returns currently selected item if any |
| onBeforeFetch | [FetchCallback](#FetchCallback) | Callback function before fetch |
| onAfterFetch | [FetchCallback](#FetchCallback) | Callback function after fetch |
## Callbacks
### RenderCallback ⇒ string
| Param | Type |
|-------|--------------------------------------------|
| item | Object |
| label | String |
| inst | [Autocomplete](#Autocomplete) |
### ItemCallback ⇒ void
| Param | Type |
|-------|--------------------------------------------|
| item | Object |
| inst | [Autocomplete](#Autocomplete) |
## ValueCallback ⇒ void
| Param | Type |
|-------|--------------------------------------------|
| value | String |
| inst | [Autocomplete](#Autocomplete) |
### ServerCallback ⇒ Promise
| Param | Type |
|----------|--------------------------------------------|
| response | Response |
| inst | [Autocomplete](#Autocomplete) |
## ErrorCallback ⇒ void
| Param | Type |
|--------|--------------------------------------------|
| e | Error |
| signal | AbortSignal |
| inst | [Autocomplete](#Autocomplete) |
## Tips
- Use arrow down to show dropdown (and arrow up to hide it)
- If you have a really long list of options, a scrollbar will be used
- Access instance on a given element with Autocomplete.getInstance(myEl)
- Use type="search" for your inputs to get a clear icon
- You can use a custom renderer to display images, for example:
```js
...
let data = [
{
"value": "My value",
"label": "My label",
"html": "
My label"
}
];
...
onRenderItem: function (item) {
return item.html;
},
```
## Groups
You can have your items grouped by using the following syntax:
```js
const src = [
{
group: "My Group Name",
items: [
{
value: "...",
label: "...",
},
],
},
];
```
## Not using Bootstrap ?
This class does NOT depends on Bootstrap JS. If you are not using Bootstrap, you can simply implement the css
the way you like it :-)
## Demo
https://codepen.io/lekoalabe/pen/MWXydNQ or see demo.html
## Custom element
You can now use this as a custom element as part of my [Formidable Elements](https://github.com/lekoala/formidable-elements) collection.
## Browser supports
Modern browsers (edge, chrome, firefox, safari... not IE11). [Add a warning if necessary](https://github.com/lekoala/nomodule-browser-warning.js/).
## Also check out
- [Bootstrap 5 Tags](https://github.com/lekoala/bootstrap5-tags): tags input for bootstrap
- [BS Companion](https://github.com/lekoala/bs-companion): the perfect bootstrap companion
- [Admini](https://github.com/lekoala/admini): the minimalistic bootstrap 5 admin panel