A jQuery UI plugin to handle multi-tag fields as well as tag suggestions/autocomplete.

Overview

Tag-it: a jQuery UI plugin

Tag-it is a simple and configurable tag editing widget with autocomplete support.

Homepage

Demo

Screenshot

Check the examples.html for several demos and the prototype.js file for a JavaScript prototype with all options and events.

Usage

First, load jQuery (v1.4 or greater), jQuery UI (v1.8 or greater), and the plugin:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/tag-it.js" type="text/javascript" charset="utf-8"></script>

If you're using a custom jQuery UI build, it must contain the Core, Widget, Position, and Autocomplete components. The Effects Core with "Blind" and "Highlight" Effect components are optional, but used if available.

The plugin requires either a jQuery UI theme or a Tag-it theme to be present, as well as its own included base CSS file (jquery.tagit.css). Here we use the Flick theme as an example:

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<link href="css/jquery.tagit.css" rel="stylesheet" type="text/css">

Now, let's attach it to an existing <ul> box:

<script type="text/javascript">
    $(document).ready(function() {
        $("#myTags").tagit();
    });
</script>

<ul id="myTags">
    <!-- Existing list items will be pre-added to the tags -->
    <li>Tag1</li>
    <li>Tag2</li>
</ul>

This will turn the list into a tag-it widget. There are several other possible configurations and ways to instantiate the widget, including one that uses a single comma-delimited input field rather than one per tag, so see the Options documentation below as well as the examples page (and its source) which demonstrates most of them, as well as the Tag-it Zendesk theme used in the screenshot above.

Theming

Tag-it is as easily themeable as any jQuery UI widget, using your own theme made with Themeroller, or one of the jQuery UI premade themes. The old ZenDesk-like theme is included as an optional CSS file (tagit.ui-zendesk.css).

Options

Tag-it accepts several options to customize its behaviour:

fieldName (String)

Each tag's hidden input field will have this name. If you're using PHP, you may want to use something like itemName[fieldName][] for this option's value.

$("#myTags").tagit({
    fieldName: "skills"
});

Defaults to tags.

availableTags (Array)

Used as source for the autocompletion, unless autocomplete.source is overridden.

$("#myTags").tagit({
    availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
});

If you define your own autocomplete.source, this option is unused (unless you choose to reference it yourself from your custom autocomplete.source of course.)

Defaults to an empty array [].

autocomplete (Object)

Allows overriding the source and select options that are set by default, as well as adding any other options you want to pass to the jQuery UI Autocomplete widget, such as minLength or delay.

The autocomplete.source should be overridden if you want to use custom autocompletion sources, like an Ajax / XHR response.

For example:

$("#myTags").tagit({
    autocomplete: {delay: 0, minLength: 2}
});

The default autocomplete.source function filters the strings in availableTags and subtracts the already assigned tags. It also positions autocomplete underneath tag input. See the full list of available options here.

showAutocompleteOnFocus (boolean)

Shows autocomplete when the tag input first receives focus, before the user even types anything.

If enabled, this will also make autocomplete.minLength default to 0 unless you override that, so that autocomplete can show up with a blank search.

Defaults to false.

removeConfirmation (boolean)

When removeConfirmation is enabled the user has to press the backspace key twice to remove the last tag. After the first keypress the last tag receives a remove css class which can be used to visually highlight the tag.

Defaults to false.

caseSensitive (boolean)

whether the duplication check should do a case sensitive check or not.

Defaults to true.

allowDuplicates (boolean)

Allows duplicate tags to be created. One implication of this is that removeTagByLabel will remove all tags which match the given label.

Defaults to false.

allowSpaces (boolean)

When allowSpaces is enabled the user is not required to wrap multi-word tags in quotation marks. For example, the user can enter John Smith instead of "John Smith".

Defaults to false.

readOnly (boolean)

When enabled, tag-it just render tags. It disables the ability to edit tags.

Defaults to false.

tagLimit (integer)

Limits the total number of tags that can be entered at once. Note that if you use this option with preloaded data, it may truncate the number of preloaded tags. Set to null for unlimited tags. See the onTagLimitExceeded callback for customizing this behavior.

Defaults to null.

singleField (boolean)

When enabled, will use a single hidden field for the form, rather than one per tag. It will delimit tags in the field with singleFieldDelimiter.

Defaults to false, unless Tag-it was created on an input element, in which case singleField will be overridden as true.

singleFieldDelimiter (String)

Defaults to ","

singleFieldNode (DomNode)

Set this to an input DOM node to use an existing form field. Any text in it will be erased on init. But it will be populated with the text of tags as they are created, delimited by singleFieldDelimiter. If this is not set, we create an input node for it, with the name given in fieldName.

Defaults to null, unless Tag-it was created on an input element, in which case singleFieldNode will be overridden with that element.

tabIndex (integer)

Optionally set a tabindex attribute on the input that gets created for tag-it user input.

Defaults to null

placeholderText (String)

Optionally set a placeholder attribute on the input that gets created for tag-it user input.

Defaults to null

Events

beforeTagAdded (function, Callback)

Can be used to add custom behaviour before the tag is added to the DOM.

The function receives a null event, and an object containing the properties tag, tagLabel, and duringInitialization.

duringInitialization is a boolean indicating whether the tag was added during the initial construction of this widget, e.g. when initializing tag-it on an input with preloaded data. You can use this to tell whether the event was initiated by the user or by the widget's initialization.

To cancel a tag from being added, simply return false in your event callback to bail out from adding the tag and stop propagation of the event.

$("#myTags").tagit({
    beforeTagAdded: function(event, ui) {
        // do something special
        console.log(ui.tag);
    }
});

afterTagAdded (function, Callback)

Behaves the same as beforeTagAdded except that it fires after the tag has been added to the DOM. It too receives the duringInitialization parameter — see beforeTagAdded for details.

beforeTagRemoved (function, Callback)

Can be used to add custom behaviour before the tag is removed from the DOM.

To cancel a tag from being removed, simply return false in your event callback to bail out from removing the tag and stop propagation of the event.

The function receives a null event, and an object with tag and tagLabel properties.

$("#myTags").tagit({
    beforeTagRemoved: function(event, ui) {
        // do something special
        console.log(ui.tag);
    }
});

afterTagRemoved (function, Callback)

Behaves the same as beforeTagRemoved except that it fires after the tag has been removed from the DOM.

onTagExists (function, Callback)

Triggered when attempting to add a tag that has already been added in the widget. The callback receives a null event, and an object containing the properties existingTag and duringInitialization, since technically you could try to preload duplicate tags during the widget initialization.

If the allowDuplicates option is enabled, this will not be triggered.

By default it will visually highlight the existing tag, unless you return false in your callback.

onTagClicked (function, Callback)

Can be used to add custom behaviour when the tag is clicked. The function receives the click event and an objecting containing tag and tagLabel properties.

$("#myTags").tagit({
    onTagClicked: function(event, ui) {
        // do something special
        console.log(ui.tag);
    }
});

onTagLimitExceeded (function, Callback)

Called when attempting to create a tag while the tag limit has already been reached. Receives a null event, and an object with the property duringInitialization. This can only be called if tagLimit is set.

Methods

assignedTags()

Returns an array of the text values of all the tags currently in the widget.

$("#myTags").tagit("assignedTags");

createTag(tagLabel, additionalClass)

Adds new tag to the list. The additionalClass parameter is an optional way to add classes to the tag element.

$("#myTags").tagit("createTag", "brand-new-tag");

preprocessTag(function, Callback)

Set a function to be called before tag is created. Callback receives the value of the tag created.

// ensure all tags are capitalized
$(#tag-it").tagit("preprocessTag", function(val) {
  if (!val) { return ''; }
  return val[0].toUpperCase() + val.slice(1, val.length);
});
// foo -> Foo

removeTagByLabel(tagLabel, animate)

Finds the tag with the label tagLabel and removes it. If no such tag is found, it'll throw an exception.

$("#myTags").tagit("removeTagByLabel", "my-tag");

removeAll()

Clears the widget of all tags — removes each tag it contains, so the beforeTagRemoved / afterTagRemoved event callbacks (if set) will be called for each.

$("#myTags").tagit("removeAll");

Properties

tagInput

The <input> field which is used for entering new tags. It's a jQuery object, so you may use it to add a class or anything to it, e.g.:

$("#myTags").data("ui-tagit").tagInput.addClass("fancy");

Authors

License

tag-it is released under the MIT license.

Comments
  • Deleting a tag throws an error

    Deleting a tag throws an error

    If you type a few tags in, then hit "backspace/delete" with your keyboard, deleting a tag throws an error in the console:

    Uncaught TypeError: Property '#' of object # is not a function

    The error is problematic in that it doesn't actually delete the tag from the internal list, so the user cannot type the tag back in if they decide they want it again. IE, I type tag "todo", delete it, then am not able to submit "todo" again. I could submit "todos" as it is a different word.

    opened by benjaminapetersen 16
  • How to get tagSource to work with $.ajax()?

    How to get tagSource to work with $.ajax()?

    Everything works so far. Except, I am unable to assign a tagSource via an ajax call.

    In firebug, the 'data' is returning:

    ["Ruby","Ruby On Rails"]
    

    But its not showing up as I type into the input box.

    $('.tags ul').tagit({
      itemName: 'question',
      fieldName: 'tags',
      removeConfirmation: true,
      availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"],
      allowSpaces: true,
      // tagSource: ['foo', 'bar']
      tagSource: function() {
        $.ajax({
          url:        "/autocomplete_tags.json",
          dataType:   "json",
          data:       { term: 'ruby' },
          success:    function(data) {
            eturn data;
          }
        });
      }
    });
    

    Am I missing something here?

    opened by krzkrzkrz 13
  • How to save tags into database?

    How to save tags into database?

    Hello, I'm a beginner in scriptingt, so i wonder how to save my added tags into my database?

    I think I need: afterTagAdded: function(event, ui), and sth like: mysql_query("INSERT INTO 'table' VALUES 'tag???'"), right? But how?

    Thanks in advance!

    opened by knzo 11
  • Uncaught TypeError

    Uncaught TypeError

    I get this error when i try to make an tag-it object, I followed the readme so it should work, or am I doing something wrong?

    Uncaught TypeError: Object function ( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); } has no method 'widget' at row 29 in tag-it.js

    opened by ghost 9
  • Changing the tagSource on the fly

    Changing the tagSource on the fly

    Is it possible to change the tagSource on the fly using AJAX? i was really wondering how would I do that since most examples here are the tag source is already given.

    opened by hitplay 7
  • Fix Tag-it preventing selection of auto-complete values via keyboard

    Fix Tag-it preventing selection of auto-complete values via keyboard

    If I configure a page with an standard <input> tag, the latest version of Tag-it and appropriate dependencies, if I try and do:

    $('input[name="search_term"]').tagit({
        allowSpaces: true,
        caseSensitive: false,
        singleField: true,
        autocomplete: 
            {source: ['one', 'two', 'three'], //typically I use an external source here
            delay: 0,
            autoFocus: true}
    });
    

    then Tag-it works, except for when I'm attempting to select an item out of the autocomplete results via hitting tab or enter on the keyboard.

    autoFocus is true, so the first item in the results is automatically selected when the autocomplete entries appear. However, after entering some text (eg thr), and hitting the Enter or Tab key, a tag is created with the thr text, rather than three, which was the entry selected within the autocomplete menu.

    This pull request ensures that during the keydown event, that a tag is only created if autocomplete isn't present/open, as the select handler for the autocomplete will handle creating the tag for us later. Previously, the keydown event was prematurely creating a tag from the half-complete input & closing the autocomplete too early.

    opened by davidjb 6
  • $(

    $("#myTags").tagit("tagInput") throws error

    Using jQuery 1.8.3:

    Error: no such method 'tagInput' for tagit widget instance

    You can access the tagInput element using the following:

    $("#myTags").data('tagit').tagInput

    Not sure if documentation should be updated to reflect this or not...

    opened by jhoff 6
  • Remove tag fix

    Remove tag fix

    Fixed a bug in removeTag which was throwing an error when tags were being deleted. Also stubbed in easing effect, will possibly work on implementing this if it seems useful to others (perhaps overkill for this widget?).

    opened by benjaminapetersen 6
  • Update tags when hidden field changes

    Update tags when hidden field changes

    How to update tags, when tag-it input value has changed?

    I want to do smth like that:

        <input name="tags" id="tags" value="hello, world" />
    
        $('#tags').tagit();
    
        $('#tags').val('hello,world,foobar');
        $('#tags').tagit('update'); // update tags based on input value
    

    Maybe there is a fork with this feature?

    opened by vanmik 6
  • Update tag-it.js

    Update tag-it.js

    Create a tag when the element loses focus. Only if option createTagOnBlur is true. Little explanation: I want to force not create tag when im switching between tab in browser. Merge this request please.

    opened by mCzolko 5
  • JS Error: Uncaught TypeError: Object function (e,t){return new v.fn.init(e,t,n)} has no method 'widget' tag-it.js:29

    JS Error: Uncaught TypeError: Object function (e,t){return new v.fn.init(e,t,n)} has no method 'widget' tag-it.js:29

    Commit Version : https://github.com/aehlke/tag-it/commit/9afa0a829ba0cf3e676b9c61a352629c692cbcb6 I get the following error mentioned in the title.

    Uncaught TypeError: Object function (e,t){return new v.fn.init(e,t,n)} has no method 'widget' tag-it.js:29

    I am using jQuery 1.8.3 and jquery-ui 1.9.2

    opened by abepark 5
  • CALL FOR MAINTAINERS

    CALL FOR MAINTAINERS

    Hi, I don't use this anymore and would like to find a few people to join as maintainers!

    I'd prefer if you can highlight previous open source you've had stewardship over, or what your stake in taking ownership of this library is, just as a simple due diligence for this long-overdue open call

    I think this is still an attractive option for its use case but has a few fundamental quality issues to resolve. And could be turned into something extra special in the right hands

    Thanks

    opened by aehlke 0
  • How to run tag-it and get the suggested values on button click?

    How to run tag-it and get the suggested values on button click?

    How to run tag-it and get the suggested values on button click?

    Here is a fiddle: http://jsfiddle.net/rzL7uvpq/1/. I would like to get the suggested dropdown after button click.

    <input id="input-newsearch">
    <button class="btn btn-default btn-newsearch" id="search-newsearch" data-toggle="tooltip">Button</button>
    
    $(document).ready(function () {
      $("#input-newsearch").tagit({
        singleField: true,
        singleFieldDelimiter: ",",
        allowSpaces: true,
        autocomplete: ({
        source: function( request, response ) {
            response ( [ { 
                id: '56',
                 label: 'Name 01'
                 },
             { id: '68',
                 label: 'Name 02'
                 },
             { id: '49',
                 label: 'Name 03'
             },
             { id: '40',
                 label: 'Name 04'
              } ] 
             );
          },
            minLength: 3,
            focus: function() {
                return false;
            },
            html: true,
            create: function(item) {
                $(this).data('ui-autocomplete')._renderItem  = function (ul, item) {
                    return $( "<li>" )
                        .append( "<a class='newsearch-label'>"+item.label+"</a>" )
                        .appendTo( ul );
                };
                $(this).data('ui-autocomplete')._renderMenu = function( ul, items ) {
                    var that = this;
                    $.each( items, function( index, item ) {
                        that._renderItemData( ul, item );
                    });
                };
            }
        })
    });
    
     $(document).on('click','.btn-newsearch', function() { 
       console.log('Test'); 
       //$('#input-newsearch').trigger("blur"); 
       //$('#input-newsearch').trigger("click"); 
       $('#input-newsearch').trigger("focus"); 
       //$('#input-newsearch').autocomplete('search'); 
       //$('#input-newsearch').autocomplete("search", ""); 
     });  
    
    }); 
    
    

    What am I missing?

    SO: https://stackoverflow.com/questions/57513734/js-jquery-run-tag-it-on-button-click-not-working

    opened by Capaman 1
  • Callback not working (Version 2.0)

    Callback not working (Version 2.0)

    $("#searchuser").tagit({
                        allowDuplicates: false,
                        tagLimit: 1,
                        availableTags: memberlist.users,
                        afterTagAdded: function (event, ui) {
    
                            // do something special
                            console.log(ui.tag);
    
                            console.log('Nyah 2');
    
                        }
                    }).on("afterTagAdded", function (event, ui) {
    
                            // do something special
                            console.log(ui.tag);
    
                            console.log('Nyah');
    
                        });
    

    I tried the classic example and the on. Nothing :c

    opened by JasminDreasond 0
  • Makes typing in input fields fun with CSS3 effects

    Fancy Input Makes typing & deleting in input/Textarea fields exciting & fun with CSS3 effects. View Demo Page Basic use example: <!-- ...previous page

    Yair Even Or 1.9k Aug 28, 2022
    typeahead.js is a fast and fully-featured autocomplete library

    typeahead.js Inspired by twitter.com's autocomplete search functionality, typeahead.js is a flexible JavaScript library that provides a strong foundat

    Twitter 16.4k Sep 19, 2022
    Add Github like mentions autocomplete to your application.

    ⚠️ Announcement ⚠️ This project was no longer maintained. You could use zurb tribute instead. An autocompletion library to autocomplete mentions, smil

    Harold.Luo 5.3k Sep 20, 2022
    Ultra lightweight, usable, beautiful autocomplete with zero dependencies.

    Awesomplete https://leaverou.github.io/awesomplete/ Awesomplete is an ultra lightweight, customizable, simple autocomplete widget with zero dependenci

    Lea Verou 6.9k Sep 15, 2022
    jQuery Form Plugin

    jQuery Form Overview The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajax

    null 5.2k Sep 19, 2022
    jQuery plugin for styling checkboxes and radio-buttons

    English description | Описание на русском jQuery-plugin for styling checkboxes and radio-buttons. With skin support. Version: 2.0.0 Project page and d

    Denis Ineshin 69 Jan 27, 2022
    Simple-load-more - This jQuery function will add a functionality to load 5 (or custom) more items. No AJAX functionality.

    Simple Load More This jQuery plugin will add a functionality to load 5 (or custom) more items. Best for lists that are long and you want to hide all e

    Zeshan Ahmed 26 Sep 2, 2022
    A plugin for Obsidian that can create input fields inside your notes and bind them to metadata fields.

    Obsidian Meta Bind Plugin This plugin can create input fields inside your notes and bind them to metadata fields. New docs I am currently working on n

    Moritz Jung 27 Aug 27, 2022
    Email Genie Allows autocomplete on email field by providing a list of domain suggestions (gmail.com, outlook.com, etc.).

    Allows users to easily and quickly complete an email field by providing a list of domain suggestions (gmail.com, outlook.com, etc.). This package stands out for its flexibility, its compatibility with libraries / frameworks, but especially its use of basic HTML and Javascript functionalities that maximize the native behavior of desktop AND mobile browsers.

    Simon Arnold 3 Jun 16, 2022
    Autocomplete - Simple accessible autocomplete for vanilla javacript with support for remote & local data, ~3KB gzip

    Autocomplete - Simple accessible autocomplete for vanilla javacript with support for remote & local data, ~3KB gzip

    Grzegorz Tomicki 46 Aug 20, 2022
    A simple library used to handle our multi-language needs.

    Vespucci Multiplayer - i18n Integration A simple library used to handle our multi-language needs. ⚠️ Important! This is a very simple implementation o

    Vespucci - România 2 Feb 7, 2022
    The best @jquery plugin to validate form fields. Designed to use with Bootstrap + Zurb Foundation + Pure + SemanticUI + UIKit + Your own frameworks.

    FormValidation - Download http://formvalidation.io - The best jQuery plugin to validate form fields, designed to use with: Bootstrap Foundation Pure S

    FormValidation 2.8k Mar 29, 2021
    A logseq plugin to extract tweets. Optionally tag the tweet's author as well.

    Logseq Twitter Extractor Plugin If this plugin helps you, I'd really appreciate your support. You can buy me a coffee here. A quick utility to parse a

    null 14 Aug 28, 2022
    Tag-input - A versetile tag input component built with Vue 3 Composition API

    TagInput A versetile tag input component built with Vue 3 Composition API. Please read this article to learn how to build this package step by step an

    Mayank 11 Jun 9, 2022
    This repo is a collection of code samples and links to previous twitch live stream sessions. If you have any ideas or suggestions for future episodes, feel free to open an issue.

    Talk DEV to me Talk DEV to me is a monthly show on twitch.tv/aws hosted by Tiago Barbosa and Alex Melnyk, where we invite customers, partners, or Amaz

    AWS Samples 101 Sep 21, 2022
    Homepage For browser, google search suggestions

    Browser Homepage ?? & Search ?? Suggestions Lightweight ⚡ and Very Fast ⚡ Set this link as your browser's homepage https://codeAbinash.github.io/homep

    Abinash Karmakar 11 Aug 18, 2022
    🌱 Ethereum provider solution for Dapp&Wallets, 🏷 If you have good suggestions, please submit issues

    English | 简体中文 | 日本 ETH Wallet Modal An Ethereum Provider Solution for Integrated Wallets and Dapps ⚠️ Notice If you need to reduce unnecessary import

    Dan Xu 33 Mar 30, 2022
    A tool that leverages the knowledge of experienced engineers to provide tech stack suggestions for your next application.

    StackGen Key technologies used React React Router and Context API PostgreSQL React Testing Library Authentication Mantine The Problem There is an over

    null 3 Jun 9, 2022
    An Obsidian plugin to grab all yaml fields from all files into a dataframe

    Metadataframe Metadataframe allows you to get all metadata from your vault into CSV file. With CSV in-hand, you can do any data analysis you want with

    null 6 May 16, 2022
    DatoCMS plugin: Translate fields

    DatoCMS plugin: Translate fields This DatoCMS plugin gives you the ability to translate structured-text, string and text fields. This plugin is an add

    De Voorhoede 3 Aug 11, 2022