Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery tag-it allow tags only from autocomplete source

Tags:

jquery

tag-it

I'm trying to implement a tag-it input except that I want to restrict the users to only select values from the autocomplete box. I tried to overried the beforeTagAdded event using the source json and check if the tag exists in the source property but no luck.

here's the code, see beforeTagAdded function.

     $(document).ready(function () {
        var itemId;
        var theTags = $('#msg_to');
        theTags.tagit({
            autocomplete: {
                source: [{ id: "1", value: 'David'}, { id: "2", value: 'John' }],
                minLength: 0,
                select: function (event, ui) {
                    itemId = ui.item.id;
                    theTags.tagit("createTag", ui.item.value);
                }
            },
            showAutocompleteOnFocus: true,
            afterTagAdded: function (event, ui) {
                if (itemId) {
                    $(ui.tag).find('input').attr('name', "tag[\'" + itemId + "']['" + ui.tagLabel + "']");
                    itemId = null;
                }
            },
            beforeTagAdded: function (event, ui) {
                var id = ui.autocomplete.source; // not working

           // what to do next?
            }
        })
    });
</script>

Thanks in advance

like image 743
Nir-Z Avatar asked Feb 13 '14 09:02

Nir-Z


1 Answers

My solution:

$(function() {     
   var currentlyValidTags = ['ac', 'dc'];
   $('input[name="_tags"]').tagit({
    availableTags: currentlyValidTags,
    autocomplete: { source: function( request, response ) {        
        var filter = removeDiacritics(request.term.toLowerCase());
        response( $.grep(currentlyValidTags, function(element) {
                        return (element.toLowerCase().indexOf(filter) === 0);
                    }));
    }},  
    beforeTagAdded: function(event, ui) {
      if ($.inArray(ui.tagLabel, currentlyValidTags) == -1) {
        return false;
      }
    }          
  });    
});
like image 75
revoke Avatar answered Sep 19 '22 02:09

revoke