Select2 callback function when

Select2 callback function when

本文关键字:when function callback Select2      更新时间:2024-05-03

我们使用Select2作为标记输入。我们需要在选择标签时触发自动保存。Select2中是否有一个回调,用于选择新的或现有的标记?

    $(".tagstypeahead").select2({
        tags: true,
        tokenSeparators: [','],
        createSearchChoice: function (term) {
            return {
                id: $.trim(term),
                text: $.trim(term) // + ' (new tag)' - Adds new tag to the end here
            };
        },
        ajax: {
            url: '/tags/typeahead.json',
            dataType: 'json',
            data: function(term, page) {
                return {
                    q: term
                };
            },
            results: function(data, page) {
                return {
                    results: data
                };
            }
        },
        // Take default tags from the input value
        initSelection: function (element, callback) {
            var data = [];
            function splitVal(string, separator) {
                var val, i, l;
                if (string === null || string.length < 1) return [];
                val = string.split(separator);
                for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
                return val;
            }
            $(splitVal(element.val(), ",")).each(function () {
                data.push({
                    id: this,
                    text: this
                });
            });
            callback(data);
        }
    });

我不认为select2有更改回调,但可以使用jQuery

在该元素上绑定一个更改事件

                $elem.unbind('change');
                $elem.change(function (e) {
                    var tags = $elem.select2('data');
                    // code  
                });