select2 JQuery dynamic JSON data with tags

#Select2 #JSON #jQuery

Table of Contents
 1          jQuery.noConflict();
 2          function formatListOptionSelection (Option, Container)
 3          {
 4             return Option;
 5          }
 6          function formatListOption (Option, Container, Query)
 7          {
 8             return "<div id='" + Option + "'>" + Option + "</div>";
 9          }
10          jQuery(document).ready(function() {
11             jQuery("#Data").select2 ({
12                multiple: true,
13                minimumInputLength: 5,
14                maximumSelectionSize: 3,
15                id: function (e) {return e;},
16                ajax: {
17                   url: 'fetch.json',
18                   // json will be used if there is no Same Origin Policy violation, otherwise JSONP shall be used
19                   dataType: 'json',
20                   data: function (term, page) {
21                      return {
22                         searchkey: term,
23                         field: 'Data'
24                      };
25                   },
26
27                   // This method will be used when the data is returned from the server
28                   results: function (data, page) {
29                      return {results: data.Datas};
30                   },
31                },
32
33                // This method will be used when you fetch result from server and add it to the element
34                formatResult: formatListOption,
35
36                // This method will be used when you select one of the options
37                formatSelection: formatListOptionSelection,
38
39                // This method will be used when you set the value attribute of the element
40                initSelection: function(element, callback) {
41                   var Datas = jQuery(element).val();
42                   Data = []
43                   jQuery(Datas.split(",")).each(function () {
44                      if (this != "") Data.push (this);
45                   });
46                   callback (Data);
47                },
48             });
49          });
50
51
52         <input class="span12" id="Data" name="Data" type="hidden" value="<Value from POST back>" />