Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/lekoala/bootstrap5-tags
Replace select[multiple] with nices badges for Bootstrap 5
https://github.com/lekoala/bootstrap5-tags
bootstrap bootstrap4 bootstrap5 checkbox es6 input javascript select tags tagsinput
Last synced: 7 days ago
JSON representation
Replace select[multiple] with nices badges for Bootstrap 5
- Host: GitHub
- URL: https://github.com/lekoala/bootstrap5-tags
- Owner: lekoala
- License: mit
- Created: 2021-05-04T20:28:05.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2024-11-27T11:03:08.000Z (2 months ago)
- Last Synced: 2025-01-19T03:55:24.311Z (14 days ago)
- Topics: bootstrap, bootstrap4, bootstrap5, checkbox, es6, input, javascript, select, tags, tagsinput
- Language: HTML
- Homepage:
- Size: 1.06 MB
- Stars: 154
- Watchers: 6
- Forks: 35
- Open Issues: 1
-
Metadata Files:
- Readme: readme.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# Tags for Bootstrap 4/5
[![NPM](https://nodei.co/npm/bootstrap5-tags.png?mini=true)](https://nodei.co/npm/bootstrap5-tags/)
[![Downloads](https://img.shields.io/npm/dt/bootstrap5-tags.svg)](https://www.npmjs.com/package/bootstrap5-tags)## How to use
An ES6 native replacement for `select` using standards Bootstrap 5 (and 4) styles.
(almost) No additional CSS needed! Supports creation of new tags.
```js
import Tags from "./tags.js";
Tags.init();
// Tags.init(selector, opts);
// You can pass global settings in opts that will apply
// to all Tags instances
```By default, only provided options are available. Validation error
will be displayed in case of invalid tag.```html
TagsChoose a tag...
Apple
Banana
OrangePlease select a valid tag.
```## Creation of new tags
Use attribute `data-allow-new` to allow creation of new tags. Their
default value will be equal to the text. Since you can enter
arbitrary text, no validation will occur.```html
```
You can force these new tags to respect a given regex.
_NOTE: don't forget the [] if you need multiple values!_
## Server side support
You can also use options provided by the server. This script expects a json response that is an array or an object with the data key containing an array.
Simply set `data-server` where your endpoint is located. It should provide an array of value/label objects. 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.You can preselect values either by using `data-selected` or by marking the suggestion as `selected` in the json result.
```html
Tags (server side)Choose a tag...
```
You can pass additionnal parameters with `data-server-params` and choose the method with `data-server-method` (GET or POST).
## Setting data programmatically
You can use the `items` config key to pass options. These will be added to the select object.
Items can be an array of Suggestions, or a key:value object.You can also call `setData` manually.
## Options
Options can be either passed to the constructor (eg: optionName) or in data-option-name format. You can also use the `data-config` attribute with a json encoded string.
| Name | Type | Description |
| -------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| items |Array.<(Suggestion\|SuggestionGroup)>
| Source items |
| allowNew |Boolean
| Allows creation of new tags |
| showAllSuggestions |Boolean
| Show all suggestions even if they don't match. Disables validation. |
| badgeStyle |String
| Color of the badge (color can be configured per option as well) |
| allowClear |Boolean
| Show a clear icon |
| clearEnd |Boolean
| Place clear icon at the end |
| selected |Array
| A list of initially selected values |
| regex |String
| Regex for new tags |
| separator |Array
\|String
| A list (pipe separated) of characters that should act as separator (default is using enter key) |
| max |Number
| Limit to a maximum of tags (0 = no limit) |
| placeholder |String
| Provides a placeholder if none are provided as the first empty option |
| clearLabel |String
| Text as clear tooltip |
| searchLabel |String
| Default placeholder |
| showDropIcon |Boolean
| Show dropdown icon |
| keepOpen |Boolean
| Keep suggestions open after selection, clear on focus out |
| allowSame |Boolean
| Allow same tags used multiple times |
| baseClass |String
| Customize the class applied to badges |
| addOnBlur |Boolean
| Add new tags on blur (only if allowNew is enabled) |
| showDisabled |Boolean
| Show disabled tags |
| hideNativeValidation |Boolean
| Hide native validation tooltips |
| suggestionsThreshold |Number
| Number of chars required to show suggestions |
| maximumItems |Number
| Maximum number of items to display |
| autoselectFirst |Boolean
| Always select the first item |
| updateOnSelect |Boolean
| Update input value on selection (doesn't play nice with autoselectFirst) |
| highlightTyped |Boolean
| Highlight matched part of the suggestion |
| highlightClass |String
| Class applied to the mark element |
| fullWidth |Boolean
| Match the width on the input field |
| fixed |Boolean
| Use fixed positioning (solve overflow issues) |
| fuzzy |Boolean
| Fuzzy search |
| startsWith |Boolean
| Must start with the string. Defaults to false (it matches any position). |
| singleBadge |Boolean
| Show badge for single elements |
| 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
| Name of the param passed to endpoint (query by default) |
| 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 |
| allowHtml |Boolean
| Allow html in input (can lead to script injection) |
| inputFilter |function
| Function to filter input |
| sanitizer |function
| Alternative function to sanitize content |
| 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 suggestion |
| onSelectItem | [ItemCallback
](#ItemCallback) | Callback function to call on selection |
| onClearItem | [ValueCallback
](#ValueCallback) | Callback function to call on clear |
| onCreateItem | [CreateCallback
](#CreateCallback) | Callback function when an item is created |
| onBlur | [EventCallback
](#EventCallback) | Callback function on blur |
| onFocus | [EventCallback
](#EventCallback) | Callback function on focus |
| onCanAdd | [AddCallback
](#AddCallback) | Callback function to validate item. Return false to show validation message. |
| onServerResponse | [ServerCallback
](#ServerCallback) | Callback function to process server response. Must return a Promise |
| onServerError | [ErrorCallback
](#ErrorCallback) | Callback function to process server errors. |
| confirmClear | [ModalItemCallback
](#ModalItemCallback) | Allow modal confirmation of clear. Must return a Promise |
| confirmAdd | [ModalItemCallback
](#ModalItemCallback) | Allow modal confirmation of add. Must return a Promise |Any of these config option can be changed later with `setConfig`.
To know more about these features, check the demo!
## Callbacks
### EventCallback ⇒
void
| Param | Type |
| ----- | -------------------------- |
| event |Event
|
| inst | [Tags
](#Tags) |### ServerCallback ⇒
Promise
| Param | Type |
| -------- | --------------------- |
| response |Response
|## ErrorCallback ⇒
void
| Param | Type |
| ------ | -------------------------- |
| e |Error
|
| signal |AbortSignal
|
| inst | [Tags
](#Tags) |### ModalItemCallback ⇒
Promise
| Param | Type |
| ----- | -------------------------- |
| label |String
|
| inst | [Tags
](#Tags) |### RenderCallback ⇒
String
| Param | Type |
| ----- | -------------------------------------- |
| item | [Suggestion
](#Suggestion) |
| label |String
|
| inst | [Tags
](#Tags) |### ItemCallback ⇒
void
| Param | Type |
| ----- | -------------------------------------- |
| item | [Suggestion
](#Suggestion) |
| inst | [Tags
](#Tags) |### ValueCallback ⇒
void
| Param | Type |
| ----- | -------------------------- |
| value |String
|
| inst | [Tags
](#Tags) |### AddCallback ⇒
void
\|Boolean
| Param | Type |
| ----- | -------------------------- |
| value |String
|
| data |Object
|
| inst | [Tags
](#Tags) |### CreateCallback ⇒
void
| Param | Type |
| ------ | ------------------------------ |
| option |HTMLOptionElement
|
| inst | [Tags
](#Tags) |## Tips
- You can also use it on single selects! :-)
- Use arrow down to show dropdown
- If you have a really long list of options, a scrollbar will be used
- Access Tags instance on a given element with Tags.getInstance(mySelect)## Style
While styling is not mandatory, some pseudo styles may help align your styles with a regular bootstrap form-control
We basically replicate input state as pseudo classes on the form-control container- Support focus styles by implementing a pseudo class `form-control-focus`
- Support improved floating labels by implementing a pseudo class `form-placeholder-shown`
- Support disabled styles by implementing a pseudo class `form-control-disabled`These styles can be found in `_tags.scss`
You can also use the `tags-pure.scss` file which provide you a css vars only version of the required styles (works well with bootstrap 5.3)
## Without Bootstrap 5
### Bootstrap 4 support
Even if it was not the initial idea to support Bootstrap 4, this component is now compatible with Bootstrap 4 because it only
requires minimal changes.Check out demo-bs4.html
### Standalone usage
Obviously, this package works great with the full bootstrap library, but you can also use it without Bootstrap or with a trimmed down version of it
Actually, this library doesn't even use the js library to position the dropdown menu, so its only dependencies is on css classes.
You can check out the .scss file to see how to reduce bootstrap 5 css to a smaller size.Check out demo-standalone.html
## Demo
https://codepen.io/lekoalabe/pen/ExWYEqx
## How does it look ?
![screenshot](screenshot.png "screenshot")
## Do you need to init this automagically ?
You can now use this as a custom element as part of my [Formidable Elements](https://github.com/lekoala/formidable-elements) collection.
Or you can use [Modular Behaviour](https://github.com/lekoala/modular-behaviour.js) ([see demo](https://codepen.io/lekoalabe/pen/wvmBLoB))
## 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
- [Bootstrap5 autocomplete](https://github.com/lekoala/bootstrap5-autocomplete): the autocomplete input for bootstrap 5 (and more!)
- [BS Companion](https://github.com/lekoala/bs-companion): the perfect bootstrap companion
- [Admini](https://github.com/lekoala/admini): the minimalistic bootstrap 5 admin panel## How to contribute
If you want to make a PR, please make your changes in `tags.js` and do not commit any build files
They will be updated upon release of a new version.If you want to test your changes, simply run `npm start` and test in `demo.html` (feel free to add new test cases).
For scss updates, apply changes to scss files. They need to be compiled manually since they are not meant to be used by themselves.