jQuery标记 - 它只允许来自自动完成源的标记

Nir*_*r-Z 6 jquery tag-it

我正在尝试实现tag-it输入,但我想限制用户只从自动完成框中选择值.我尝试使用源json覆盖beforeTagAdded事件,并检查源属性中是否存在标记,但没有运气.

这是代码,请参阅beforeTagAdded函数.

     $(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>
Run Code Online (Sandbox Code Playgroud)

提前致谢

rev*_*oke 5

我的解决方案

$(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;
      }
    }          
  });    
});
Run Code Online (Sandbox Code Playgroud)


小智 1

有一个 tag-it 的分支可以做你想做的事:

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

它有一个 requireAutocomplete 设置。

(我必须合并两个版本,因为我需要每个版本的东西......但希望这会对你有所帮助。)