3

We are using Select2 for a tags input. We need to trigger autosave whenever a tag is selected. Is there a callback in Select2 for when a new or existing tag is selected?

    $(".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);
        }

    });
Ben
  • 4,301
  • 6
  • 37
  • 61

1 Answers1

0

I don't think select2 has a change callback, but you can do it with jQuery

Bind a change event on that element

                $elem.unbind('change');
                $elem.change(function (e) {
                    var tags = $elem.select2('data');
                    // code  
                });
Cosmin
  • 2,184
  • 21
  • 38