Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tagit : limiting tag creation to the given list by ajax

i am using a jquery ui plugin for tagging :

https://github.com/aehlke/tag-it

im having a few issues :

  1. when a user selects from the list, i want to save the id and the value for that tag.

  2. only create tags from the list brought back by the AJAX call

    $(function() {
      $('#tags').tagit({tagSource:function( request, response ) {
    $.ajax({
    type:"GET",
    url: "http://some_link",
    dataType: "jsonp",
    data:{
        term:request.term,
        }, 
        success: function( data ) {
            response( $.map( data, function( item ) {
                return {
                    label: item.label,
                    value: item.value,
                    id:item.id
                };  
            }));
        }   
        });
    }
    , triggerKeys: ['enter', 'comma', 'tab']});
    });
    
like image 588
Nauman Bashir Avatar asked Apr 12 '12 11:04

Nauman Bashir


1 Answers

In answer to your second question Chris Leishman's fork of the Tag-It repository contains a new property requireAutocomplete which allows only items in the autocomplete list to be used as tags.

You can find his pull request here: https://github.com/aehlke/tag-it/pull/37

Download this version of the JS file from: https://github.com/chrisleishman/tag-it

and use it like an ordinary property:

$(selector).tagit({
        requireAutocomplete: true,
        tagSource: [...]
});

As for your first question, I'm working on this myself so I'll update my answer when I've found a solution.

I've made an amendment to my own local TagIt.js at line 271 changing:

var tag = that.createTag(ui.item.value);

to

var tag = that.createTag(ui.item.label);

which fixed the issue whereby the Id of the items shows instead of the label after choosing an option from the autocomplete list.

Update

Here's some information on how to save the ID's of each tag.

The first thing I did was override the createTag method to include a labelName parameter (you can modify the origional if you want, I just prefered to override it).

$.ui.tagit.prototype.createTag = function (labelName, value, additionalClass) {
 // The origional code from createTag here
}

Trim the labelName in the same way that the current value param is trimmed:

value = $.trim(value);
labelName = $.trim(labelName)

Change the label variable to use the new labelName:

    var label = $(this.options.onTagClicked ? 
      '<a class="tagit-label"></a>' :
      '<span class="tagit-label"></span>').text(labelName);

In the autocomplete section of the origional source I change the call to createTag to include the new label:

var tag = that.createTag(ui.item.label, ui.item.value);
like image 155
Jamie Dixon Avatar answered Sep 26 '22 12:09

Jamie Dixon