3

I am using the jQuery plugin Tag-It for handling auto-suggestion and tagging. I am getting the data using an Ajax call which is working fine.

The data at the moment is being returned in the following format:

{"itemID":"ItemName"}

For example:

{"1":"Yellow","2":"Green"}

This is going fine.

What I want to do is have the user click on the returned tag, and have the data stored in the hidden field something like this:

<input type="hidden" name="tag['itemID']['itemName']"/>

I can't seem to figure out how to do it, has anyone any experience with this and able to point me in the right direction?

krock
  • 28,904
  • 13
  • 79
  • 85
Amo
  • 2,884
  • 5
  • 24
  • 46
  • When you say that the data is returned by Ajax, do you mean that you are using the autocomplete feature to get the list of tags available to add? – Liam Dec 13 '12 at 11:43

1 Answers1

3

To do this requires passing the extra data that is returned from the autocomplete Ajax call to the Tag-it tag events.

Add a variable itemId to a scope, which will be used to store the additional data from the autocomplete item:

{
    var itemId;

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: [{id:1,value:'New 1'},{id:2,value:'New 2'}],
            select: function(event,ui) {
                itemId = ui.item.id;
                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 (itemId) {
                $(ui.tag).find('input')
                     .attr('name', "tag[\'" + itemId+ "']['" + ui.tagLabel + "']");
                itemId = null;
            }
        }
    });
}

See a working example of this solution at http://jsfiddle.net/DCJsj/

Liam
  • 2,004
  • 2
  • 17
  • 18