Tag Handler is a jQuery plugin used for managing tag-type metadata.

Basic Usage Instructions

Plugin Setup and Usage Examples

Note: the ajax examples are using mockjax (http://github.com/appendto/jquery-mockjax) as the backend rather than a live server.

 

Default Usage

The Tag Handler will be initialized with no options and no default tags:

    $("#array_tag_handler").tagHandler();
    

Jquery UI Theme Usage

The Tag Handler will be initialized to use the JQuery UI Theme. Loaded theme: Smoothness

    $("#array_tag_handler").tagHandler({jqueryTheme: true});
    

Auto-complete

The Tag Handler will be initialized with preset tags from the assignedTags and availableTags arrays, and autocomplete witll be turned on:

    $("#example_autocomplete").tagHandler({
        assignedTags: [ 'C', 'Perl', 'PHP' ],
        availableTags: [ 'C', 'C++', 'C#', 'Java', 'Perl', 'PHP', 'Python' ],
        autocomplete: true
    });
    

Ajax

The Tag Handler will be initialized and pull data via ajax, also sending some data to the server:

    $("#example_ajaxinit").tagHandler({
        getData: { id: 'user123', type: 'user' },
        getURL: '/ajaxtest/get',
        autocomplete: true
    });
    

Ajax with Save

Same as the example above, but a different user is set in the getData/UpdateData options and now the tags will save when clicking the save button

    $("#example_ajax_with_save").tagHandler({
        getData: { id: 'user234', type: 'user' },
        getURL: '/ajaxtest/get',
        updateData: { id: 'user234', type: 'user' },
        updateURL: '/ajaxtest/update',
        autocomplete: true
    });
    

Ajax with Auto Update

Same as the example above, but autoUpdate is true, tags will save automatically (no save button will be shown)

    $("#example_ajax_with_auto_update").tagHandler({
        getData: { id: 'user234', type: 'user' },
        getURL: '/ajaxtest/get',
        updateData: { id: 'user234', type: 'user' },
        updateURL: '/ajaxtest/update',
        autocomplete: true,
        autoUpdate: true
    });
    

Ajax load tags on demand

The Tag Handler will be initialized but it will request the tag list when the user writes more than 2 chars (try typing in a mixed drink name for this example):

    $("#example_ajax_on_demand").tagHandler({
        getData: { id: 'user345', type: 'user' },
        getURL: '/ajaxtest/search',
        autocomplete: true,
        initLoad: false,
        minChars: 2
    });
    

Prevent Adding New Tags

Adding allowAdd: false will prevent the user from being able to add new tags.

    $("#example_prevent_add_new").tagHandler({
        assignedTags: [ 'C', 'Perl', 'PHP' ],
        availableTags: [ 'C', 'C++', 'C#', 'Java', 'Perl', 'PHP', 'Python' ],
        autocomplete: true,
        allowAdd: false
    });
    

Using Add and Delete Callbacks

The following example shows how to use add and delete callbacks. A call back returning false will stop the default process.

    $("#example_with_callbacks").tagHandler({
        assignedTags: [ 'C', 'Perl', 'PHP' ],
        availableTags: [ 'C', 'C++', 'C#', 'Java', 'Perl', 'PHP', 'Python' ],
        autocomplete: true,
        onAdd: function(tag) { alert('Added tag: ' + tag); },
        onDelete: function(tag) { alert('Deleted tag: ' + tag); }
    });
    

Using a custom tag validator

The following example shows how to can pass in your own validation checks. This check is a callback that must return true if the tag is valid, or false if the tag fails inspection. The validator in this example uses regex to validate that only numbers are added to the tags.

    $("#example_with_custom_validator").tagHandler({
        onIsValid: function(newTag) {
            if (/^[0-9]+$/.test(newTag)) {
                alert("Tag Passed!");
                return true;
            }
            alert("This new tag is not a valid number entered: "+newTag);
            return false;
        }
    });
    

Using the afterLoad Call Handler

The following example shows how to can pass in your own init callback. This call will be called after the tagHandler is loaded.

    $("#example_with_after_load_callback").tagHandler({
        afterLoad : function() { alert("TagHandeler Loaded!") }
    });
    

Setting maximum number of tags

The following example shows how to set the maximum number of allowed tags

    $("#example_with_maximum").tagHandler({
        assignedTags: [ 'Perl' ],
        availableTags: [ 'C', 'C++', 'C#', 'Java', 'Perl', 'PHP', 'Python' ],
        autocomplete: true,
        maxTags:5
    });
    

Plugin Methods

These are convenience methods for dealing with the Tag-Handler.

Note: clicking the example buttons will show any output as an alert and in the console.log.

$("#some_selector).tagHandler('getTags')

Click on the button "Get Tags" to show an alert of active tags

    var tags = $("#some_selector).tagHandler('getTags');

    /* Do something with tags array */
    alert(tags.join(,));
    

$("#some_selector).tagHandler('getSerializedTags')

Click on the button "Get Serialized Tags" to show an alert of active tags

    var tags = $("#some_selector).tagHandler('getSerializedTags');

    /* Do something with tags array */
    alert(tags);
    

$("#some_selector).tagHandler('getOptions')

Click on the button "Get Options" to show an alert of all tags available

    var tags = $("#some_selector).tagHandler('getOptions');

    /* Do something with tags array */
    alert(tags.join(,));
    

$("#some_selector).tagHandler('getSerializedOptions')

Click on the button "Get Serialized Options" to show an alert of all tags available

    var tags = $("#some_selector).tagHandler('getSerializedOptions');

    /* Do something with tags array */
    alert(tags);
    

$("#some_selector).tagHandler('addTag', 'New Tag')

Click on the button "Add Tag" to add a tag to the tag handler

    $("#some_selector).tagHandler('addTag', 'New Tag');
    

$("#some_selector).tagHandler('addOption', 'New Tag')

Click on the button "Add Option" to add a tag to the list of available tags

    $("#some_selector).tagHandler('addOption', 'New Tag');
    

$("#some_selector).tagHandler('destroy')

Destroy an active tag handler and return it to its original state

    $("#some_selector).tagHandler('addOption', 'New Tag');
    

$("#some_selector).tagHandler('reload')

Restart the tag handler. Make some changes and hit the Reload button to restore to it's original state. This function will also make the ajax calls to re-initialize the tag handler as well. Note: All unsaved changes will be lost!

    $("#some_selector).tagHandler('reload');
    

Plugin Options

Tag data specific options:

Option Description Default Value
assignedTags array to pass a list of already assigned tags []
availableTags array to pass a list of all available tags []
getData data field with additional info for getURL {}
getURL URL for retrieving tag lists via ajax "e;"e;
initLoad indicates if all tags should be loaded on init true
updateData data field with additional info for updtateURL {}
updateURL URL for saving tags via ajax "e;"e;

Callback options:

Option Description Default Value
afterAdd function to be called after a new tag is added {}
afterDelete function to be called after a tag is deleted {}
onAdd function to be called when a new tag is added -- if a false value is returned, the add will fail {}
onDelete function to be called when a tag is deleted {}
onIsValid function to be called for custom validation of tags. Must return true if tag passes inspection or false if it fails. {}

Miscellaneous options

Option Description Default Value
allowAdd indicates whether the user can add new tags true
allowEdit indicates whether the tag list is editable true
autocomplete activates autocomplete dropdown functionality for tag name - requires jqueryui autocomplete plugin false
autoUpdate indicates whether updating occurs automatically whenever a tag is added/deleted - if set true, the save button will not be shown false
className base class name that will be added to the tag container tagHandler
debug will turn on some console logging debug information false
delimiter extra delimiter to use to separate tags - note 'enter', 'comma', and 'tab' are always allowed false
maxTags sets a limit to the number of allowed tags, set to 0 to allow unlimited 0
minChars minimum number of chars to type before starting autocomplete 0
msgError message shown when there is an error loading the tags There was an error getting the tag list.
msgNoNewTag message shown when the user cannot add a new tag You don't have permission to create a new tag.
msgMaxTags message shown when the user has reached the maximum amount of tags allowed Maximum tags allowed:
queryname query term used to send user typed data to the server q
sortTags sets sorting of tag names alphabetically true
jqueryTheme Use the Jquiry UI Theme instead of default false

Plugin Methods

Method Description Usage
getSerializedTags Will return a comma separated string of the currently assigned tags for the object. .tagHandler("getSerializedTags")
getTags Will return an array of the currently assigned tags for the object. .tagHandler("getTags")
getSerializedOptions Will return a comma separated string of all available options. Includes the current selected tags well. .tagHandler("getSerializedOptions")
getOptions Will return an array of all available options. Includes the current selected tags well. .tagHandler("getTags")
addTag Will add a new tag to the list of assigned tags. .tagHandler("addTag", "New Tag")
removeTag Will remove a tag from the list of assigned tags and move it to the available tags instead. .tagHandler("removeTag", "Tag To Remove")
addOption Will add a tag to the list of available tags. .tagHandler("addOption", "New Option")
saveTags Will force a save of current tags. Only works if updateURL is passed in .tagHandler("saveTags")
destroy Destory a current taghandler and restore the selector to it's initial state .tagHandler("destroy")
reload Return the tagHandler to it's inital state. See example above for more details .tagHandler("reload")
version Returns the version of the TagHandler .tagHandler("version")

适用浏览器:IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗.

来源:站长素材