Reputation: 620
We are using Tag-it with an Ajax call as a tagSource
for tagging content. We need to include more data than the tag label itself, e.g. an id different than the label or metadata such as type of tag. Data that is returned to the Ajax call but we wouldn't like to include in the tag label itself.
We could modify Tag-it to include data with li
items using jQuery's .data
method but if someone else already have solved this or can recommend another tag library it would be highly appreciated.
Upvotes: 3
Views: 1312
Reputation: 2024
The key to doing this without modifying Tag-it is to bridge the gap between the extra data that is returned from the autocomplete Ajax call and the Tag-it afterTagAdded event.
Add a variable itemData
to a scope, which will be used to store the additional data from the autocomplete item:
{
var itemData;
Get a reference to the tags element so that the create tag behavior can be called
var theTags = $('#tags');
theTags.tagit({
Handle the select
event of the autocomplete and store the additional data from the selected autocomplete item, then create the tag.
autocomplete: {
source: [
{value:'User Tag',data:{id: 1, type: 'userTag'}},
{value:'System Tag',data:{id: 2, type: 'systemTag'}}
],
select: function(event,ui) {
itemData = ui.item.data;
theTags.tagit("createTag", ui.item.value);
return false;
}
},
Handle the afterTagAdded
event for Tag-it. In here any custom behavior to modify the just added tag can be implemented.
afterTagAdded: function(event, ui) {
if (itemData) {
$(ui.tag).data('type', itemData); // store all data
$(ui.tag).find('input').val(itemData.id); // use a bit of the data
itemData = null;
}
}
});
}
See a working example of this solution at http://jsfiddle.net/yuhxL/2/
Upvotes: 3