【问题标题】:Exclude existing tags from Select2 search results从 Select2 搜索结果中排除现有标签
【发布时间】:2019-11-20 20:58:12
【问题描述】:

我正在使用 Select2 ("select2": "^4.0.6-rc.1"),如下所示,它大部分都运行良好。

但现在这是我们要防止的情况:

管理员想要添加 TagXyz,但没有看到这个标签已经存在(因为已经有很长的选定标签列表),所以开始输入标签的名称,然后按 Enter,以为他添加了标签,但实际上,它会删除现有标签,因为它已经存在!

如何从 Select2 搜索结果中排除现有标签(或以其他方式实现我的目标)?

我想也许我应该添加matcher: matchCustom,(如docs 中所建议的那样)并使我的 matchCustom 排除当前标签。

因此,作为我的 matchCustom 函数的起点,我尝试将 matcher 函数复制到 https://github.com/select2/select2/blob/4.0.6-rc.1/dist/js/select2.js#L4931,但发现我需要访问 stripDiacritics 函数。

我该怎么办?

var tagsSelect = $('select[name=tags]');
tagsSelect.select2({
    placeholder: 'Choose tags here',
    tokenSeparators: [',', ' '], //https://select2.org/tagging
    theme: "classic",
    width: "style" //element, style, resolve, or '<value>' https://select2.org/appearance#container-width
}).on('select2:select', function (e) {
    var data = e.params.data;
    addTag($(this).attr('data-contactId'), data.id, data.text);// https://select2.org/programmatic-control/events
}).on('select2:unselect', function (e) {
    var data = e.params.data;
    var contactTagId = data.element.getAttribute('data-contacttagid');//https://stackoverflow.com/a/30850437/470749
    removeTag(contactTagId, data.text); // https://select2.org/programmatic-control/events
}).on('select2:unselecting', function (event) {       
    var label = event.params.args.data.text;       
    var opt = tagsSelect.find('option[value="' + event.params.args.data.id + '"]').first();
    if (opt.is(':disabled')) {
        event.preventDefault();
    }
}).on('change', function (event) {
    changeClassOfDisabledTags();
});

【问题讨论】:

    标签: jquery-select2 jquery-select2-4


    【解决方案1】:

    我想我解决了。

    const DIACRITICS = require('select2/src/js/select2/diacritics.js');
    
    function stripDiacritics(text) {
        // Used 'uni range + named function' from http://jsperf.com/diacritics/18
        function match(a) {
            return DIACRITICS[a] || a;
        }
        return text.replace(/[^\u0000-\u007E]/g, match);
    }
    

    那么这是我的 matchCustom 的相关部分:

    if (original.indexOf(term) > -1) {
        var modifiedData = $.extend({}, data, true);
        //modifiedData.text += ' (matched)';
    
        // You can return modified objects from here
        // This includes matching the `children` how you want in nested data sets
        if (modifiedData.selected) {
            return null;//exclude existing (selected) tags from search results
        } else {
            return modifiedData;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2020-10-08
      • 1970-01-01
      相关资源
      最近更新 更多