Tag-it onlyAvalaibleTags option doesn't work

2019-05-17 00:29发布

I use tag-it plugin from https://github.com/aehlke/tag-it/downloads. How to disable adding new tags?

$(document).ready(function () {
                $("#Tags").tagit({
                    singleField: true,
                    singleFieldNode: $('#mySingleField'),
                     //  onlyAvailableTags : true,
                     allowNewTags: false,
                    tagSource: [@Html.Raw(ViewBag.AvailableTags)]
                });
            });

I tried to use onlyAvailableTags : true and allowNewTags: false options, but there's no effect.

3条回答
趁早两清
2楼-- · 2019-05-17 01:14

Since you say "but there's no effect", I would guess that @Html.Raw(ViewBag.AvailableTags) produces an output that that breaks the javascript syntax. The tags need to be in quotes, otherwise they are treated as variables.

Incorrrect output:

tagSource: [my-tag, another-tag]

Server-side, I assume you have some kind of IEnumerable<string>:

ViewBag.AvailableTags = new List<string>
{
    "my-tag",
    "another-tag",
};

Then, in your .cshtml:

tagSource: ["@string.Join("\", \"", ViewBag.AvailableTags)"]

This would produce the correct output:

tagSource: ["my-tag", "another-tag"]

That would be what I'd try first.

查看更多
倾城 Initia
3楼-- · 2019-05-17 01:27

This is what I did for the latest version of tag-it :

var tags_list = ['tag1', 'tag2, 'tag3];

$("input[name='subject-tags']").tagit({
    availableTags : tags_list,
    beforeTagAdded : function(event, ui) {
        if(tags_list.indexOf(ui.tagLabel) == -1){
            return false;
        }
    }
});

Tried to make it cleaner by implementing

$("input[name='subject-tags']").tagit({
    availableTags : ['tag1', 'tag2, 'tag3],
    beforeTagAdded : function(event, ui) {
        if(this.availableTags.indexOf(ui.tagLabel) == -1){
            return false;
        }
    }
});

But this.availableTags doesn't return the array (return : undefined). I'm a JS noob, so something must be wrong with the way I access the property.

查看更多
在下西门庆
4楼-- · 2019-05-17 01:30

I found that by commenting out:

 // Autocomplete will create its own tag from a selection and close automatically.
 if (!that.tagInput.data('autocomplete-open')) {
    that.createTag(that._cleanedInput());
 }

And:

// Create a tag when the element loses focus.
// If autocomplete is enabled and suggestion was clicked, don't add it.
if (!that.tagInput.data('autocomplete-open')) {
     that.createTag(that._cleanedInput());
}

It removes this functionality. Perhaps not the cleanest way of doing it, but it works.

Just comment out the if(){ } loops.

查看更多
登录 后发表回答