问题
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.
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/8396369/tag-it-onlyavalaibletags-option-doesnt-work