Categories: CSSScriptWeb Design

Lightweight Tag Input Component with Autocomplete – input-tags-js

Input Tags JS is a vanilla JavaScript library that turns a standard <input type=”text”> field into a full-featured tags input component with autocomplete suggestions.

It supports predefined tag lists, group-based exclusivity rules, custom user-defined tags, and keyboard navigation, all with no external dependencies.

Features:

  • Autocomplete: Shows a filtered list of known tags as the user types, updated on each keystroke.
  • Sponsored
  • Alias support: Each tag can carry one or more alternate search strings.
  • Group-based exclusivity: Selecting one tag in a group automatically blocks others from the same group.
  • Custom tag input: Allows your users to add tags not found in the predefined list, with a configurable blacklist to block specific values.
  • Keyboard Navigation: Up and Down arrows move focus between suggestions. Enter or comma commits a tag. Backspace at the start of the field removes the last tag.
  • Hidden field output: Submits tag data via hidden <input> fields, including separate tracking of added tags, added custom tags, and removed tags.

Use Cases:

  • Forum Post Tagging: Let users categorize discussions with relevant topic tags.
  • Blog Article Categorization: Provide editors with a controlled vocabulary of categories and tags.
  • Issue Tracker Labels: Implement tag-based labeling for bug reports and feature requests.
  • Product Filtering Search: Build a search UI where users add filter tags dynamically.

How To Use It:

1. Add the required InputTags.js and InputTags.css files to your HTML page.

<!-- Tag input stylesheet -->
<link rel="stylesheet" href="InputTags.css" media="all" />

<!-- Tag input script -->
<script src="InputTags.js"></script>

2. Place a standard text input inside a <form> element. The library requires the input to live inside a form. It will throw an error if it doesn’t find one.

<form id="recipe-form">
  <input type="text" id="recipe-tags" placeholder="Add dietary tags" />
</form>

3. Call the InputTags.enable() method and pass your configuration settings & predefined tags. We use a recipe tagging system for this example.

const myTagsInstance = InputTags.enable(
  'recipe-tags',[
    // Standard predefined tags
    {id: 'vegan', className: 'diet', label: 'Vegan'},
    {id: 'keto', className: 'diet', label: 'Keto'},
    // Tag with an alias for easier searching
    {id: 'gluten-free', className: 'diet', label: 'Gluten-Free', alias: 'gf'},
    // Grouped tags (users can only select one from this group)
    {id: 'breakfast', group: 'Meal Type', label: 'Breakfast'},
    {id: 'lunch', group: 'Meal Type', label: 'Lunch'},
    {id: 'dinner', group: 'Meal Type', label: 'Dinner'}
  ],
  {
    // Allow custom tags and block specific unwanted words
    name: 'user_custom_tags[]',
    blacklist: ['spam', 'test']
  }
);

4. InputTags.enable(settings, knownTags [, customTags]) accepts three parameters. The settings object supports the following properties:

  • element (string | HTMLElement): The id of the target <input type="text"> element, or the element itself.
  • name (string, optional): The form field name used for the hidden tag inputs. Defaults to tags. The library appends [] automatically.
  • maxTags (number, optional): The maximum number of tags a user can add. Defaults to 10. Set to 0 for no limit.
  • maxSuggestions (number, optional): The maximum number of autocomplete suggestions shown in the popover. Must be between 1 and 20. Defaults to 20.

5. The knownTags array accepts objects with these properties per tag:

  • id (string | number): A unique identifier for the tag. Used as the hidden field value.
  • label (string): The display text shown in the tag pill and the autocomplete popover.
  • alias (string | string[], optional): One or more alternate strings the autocomplete will match against.
  • group (string | number, optional): A group name. Only one tag per group is allowed to be active at a time.
  • className (string, optional): An extra CSS class added to the tag pill span for custom styling.

6. The optional customTags parameter accepts:

  • name (string, optional): The form field name for custom tag hidden inputs. Defaults to tags_custom.
  • blacklist (string | string[], optional): A list of slugged strings to block from being added as custom tags.

7. API methods.

Sponsored
// Add a new tag programmatically
myTagsInstance.addTag('spicy', 'Extra Spicy');

// Remove a specific tag by its ID value
myTagsInstance.removeTag('keto');

// Remove a tag based on its position in the list (0-indexed)
myTagsInstance.removeTagByIndex(1);

// Clear all currently selected tags
myTagsInstance.removeTags();

// Retrieve an array of objects containing the current tags
const activeTags = myTagsInstance.getCurrentTags();
console.log(activeTags);

// Replace the predefined tags with a new dataset
myTagsInstance.setKnownTags([
  {id: 'snack', label: 'Snack'},
  {id: 'dessert', label: 'Dessert'}
]);

// Force the DOM elements to update
myTagsInstance.refresh();

Alternatives:

FAQs:

Q: Can I pre-populate the tag input with existing tags when editing a record?
A: Yes. Call tagInput.setInitialTags([id1, id2, id3]) after initialization. Pass an array of tag ids matching your knownTags definitions.

Q: The popover doesn’t appear after I dynamically update the page. What’s wrong?
A: Call tagInput.refresh() after any DOM change that affects the component’s container. The library builds its internal structure at initialization time. If external code moves or re-renders the surrounding DOM, the popover’s positioning context can break. refresh() rebuilds the pill list and re-attaches the component to the current DOM state.

Q: Can I load the known tags list from an API call instead of hardcoding it?
A: Yes. Call InputTags.enable() with an empty array as the second argument to start. Once your API response arrives, call tagInput.setKnownTags(responseArray) to replace the tag list at runtime.

Q: How do I prevent users from adding duplicate or conflicting tags?
A: The library handles duplicates automatically. It blocks any tag whose id is already in the active list. For conflicting tags (e.g., “Open” and “Closed” status), assign both to the same group value in your tag definitions. The library will only allow one tag per group to be active at a time.

Q: Does Input Tags JS work with forms that submit via Fetch or XMLHttpRequest?
A: Yes. The library stores all tag data in hidden <input> fields inside the <form>. Read them with new FormData(formElement) before your Fetch call. The tags[], tags_added, tags_removed, and custom_tags[] fields will all be present and accurate.

The post Lightweight Tag Input Component with Autocomplete – input-tags-js appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

AliExpress Has a 1,000W Peak 48V Adult Electric Bike for $288 with Free Delivery (Ships From the US)

Looking for a powerful ebike with the speed and range to meet your ambitious needs?…

46 minutes ago

Save 50% Off the 3.8lb Lenovo IdeaPad Pro 16″ Ultra-Portable Laptop with Discrete GPU, Now Just $750

Lenovo is offering a great deal on an ultra-portable productivity laptop that can also do…

47 minutes ago

Apple’s New Entry-Level MacBook Neo Is Up for Preorder Starting at $599

For the first time in years, Apple has introduced a new MacBook in its laptop…

47 minutes ago

The MacBook Neo and Everything Else Apple Announced This Week

In lieu of a polished livestream of a heavily produced, pre-recorded announcement of new stuff,…

48 minutes ago

Lanterns HBO TV Series Cast and Characters: Who’s Confirmed for the DC Show?

Lanterns is one of the big shows that will be part of the first phase…

50 minutes ago

Rockford man sentenced to probation for gun and cannabis offenses

Tszarian Wright pleaded guilty to weapon possession and selling drugs and was sentenced to 6…

1 hour ago

This website uses cookies.