Вопрос

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?

Это было полезно?

Решение

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/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top