Git Product home page Git Product logo

bootstrap5-tags's Introduction

Tags for Bootstrap 4/5

NPM Downloads

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.

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.

<label for="tags-input" class="form-label">Tags</label>
<select class="form-select" id="tags-input" name="tags[]" multiple>
  <option disabled hidden value="">Choose a tag...</option>
  <option value="1" selected="selected">Apple</option>
  <option value="2">Banana</option>
  <option value="3">Orange</option>
</select>
<div class="invalid-feedback">Please select a valid tag.</div>

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.

<select class="form-select" id="tags-input" name="tags[]" multiple data-allow-new="true"></select>

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.

<label for="validationTagsJson" class="form-label">Tags (server side)</label>
<select
  class="form-select"
  id="validationTagsJson"
  name="tags_json[]"
  multiple
  data-allow-new="true"
  data-server="demo.json"
  data-live-server="1"
>
  <option disabled hidden value="">Choose a tag...</option>
</select>

You can pass additionnal parameters with data-server-params and choose the method with data-server-method (GET or POST).

Options

Options can be either passed to the constructor (eg: optionName) or in data-option-name format.

Name Type Description
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 | String A comma separated list of 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
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
fullWidth Boolean Match the width on the input field
fixed Boolean Use fixed positioning (solve overflow issues)
activeClasses Array By default: ["bg-primary", "text-white"]
labelField String Key for the label
valueField String Key for the value
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
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 function Callback function that returns the suggestion
onSelectItem function Callback function to call on selection
onClearItem function Callback function to call on clear
onCanAdd function Callback function to validate item. Return false to show validation message.
onServerResponse function Callback function to process server response. Must return a Promise

To know more about these features, check the demo!

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

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

Do you need to init this automagically ?

You can use Modular Behaviour

https://codepen.io/lekoalabe/pen/wvmBLoB

Browser supports

Modern browsers (edge, chrome, firefox, safari... not IE11). Add a warning if necessary.

Also check out

bootstrap5-tags's People

Contributors

lekoala avatar un0tec avatar mariusa avatar fahmij8 avatar dazzar56 avatar kuboon avatar hoytron avatar edika99 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.