How do I store additional data along with Tag-it tags?
We use Tag-it with an Ajax call tagSource
to tag the content. We need to include more data than the tag label itself, for example. id other than a label or metadata such as a tag type. The data that is returned in the Ajax call, but we don't want to be included in the label tag itself.
We can change Tag-it to include data with elements li
using the jQuery.data
method , but if someone has already solved this or can recommend a different library tag it would be much appreciated.
source to share
The key to doing this without changing the tag is to close 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 the scope that will be used to store additional data from the autocomplete element:
{
var itemData;
Get a reference to the tags element so that create tag behavior can be created
var theTags = $('#tags');
theTags.tagit({
Handle the select
autocomplete event and save 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 event afterTagAdded
for Tag-it. Any custom behavior can be implemented here to change just the added tag.
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/
source to share