title: Select2 callback function when
body: <p>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?</p>
  
  <pre><code>    $(".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 &lt; 1) return [];
                  val = string.split(separator);
                  for (i = 0, l = val.length; i &lt; l; i = i + 1) val[i] = $.trim(val[i]);
                  return val;
              }
  
              $(splitVal(element.val(), ",")).each(function () {
                  data.push({
                      id: this,
                      text: this
                  });
              });
  
              callback(data);
          }
  
      });
  </code></pre>