JavaScript APIs

Tags Input

The JavaScript API for the Tags Input component.

The mod.tags_input() method initializes a tags input component for a specific element and handles interaction events for adding and removing tags.

Method API

// Using mod(-plus).iife.min.js
window.mod.tags_input(element: HTMLElement, options: object);

// Using mod(-plus).esm.min.js
import { tags_input } from 'path/to/mod(-plus).esm.min.js';
tags_input(element: HTMLElement, options: object);

Usage Examples

Use the following usage examples to guide your implementation.

Examples Use Global JavaScript

For simplicity, all usage examples demonstrate usage with Mod's global JavaScript library (mod(-plus).iife.min.js). All documented behavior is identical in the ESM variant of Mod's JavaScript library.

Tags Input HTML

<div class="mod-tags-input"></div>

Tags Input JavaScript

const element = document.querySelector('.mod-tags-input');

const tags_input_instance = window.mod.tags_input(element, {
  tags: ['apple', 'banana', 'mango', 'pear'],
  events: {
    on_add_tag: (tag, tags) => {
      console.log('Added tag:', tag);
      console.log('Current tags:', tags);
    },
    on_remove_tag: (tag, tags) => {
      console.log('Removed tag:', tag);
      console.log('Current tags:', tags);
    }
  }
});

// Use the returned methods
console.log('Current tags:', tags_input_instance.get_tags());
tags_input_instance.add_tag('new-tag');
tags_input_instance.clear_tags();

API

element HTMLElement required
Container element for the tags input. The input element is automatically created and managed by the component.
options object
Configuration options for the tags input.
tags array
Initial array of tags to populate the input with.
placeholder string
Placeholder text for the input element. Defaults to 'Type and press Enter to add tags...'.
input object
Configuration options for the input element.
classes string
CSS classes to apply to the input element. Defaults to 'mod-input'.
events object
Event callbacks for tag actions.
on_add_tag function
Callback function when a tag is added. Receives (tag, tags_array) as parameters.
on_remove_tag function
Callback function when a tag is removed. Receives (tag, tags_array) as parameters.

Return Value

The tags_input() method returns an object with the following methods:

get_tags function
Returns an array of all current tags as strings.
add_tag function
Programmatically adds a tag. Takes a string parameter for the tag to add.
clear_tags function
Removes all tags from the input component.
set_tags function
Replaces all current tags with a new array of tags. Takes an array of strings as parameter.