Thursday, April 4, 2013

select2 JQuery dynamic JSON data with tags


          jQuery.noConflict();
          function formatListOptionSelection (Option, Container)
          {
             return Option;
          }
          function formatListOption (Option, Container, Query)
          {
             return "<div id='" + Option + "'>" + Option + "</div>";
          }
          jQuery(document).ready(function() {
             jQuery("#Data").select2 ({
                multiple: true,
                minimumInputLength: 5,
                maximumSelectionSize: 3,
                id: function (e) {return e;},
                ajax: {
                   url: 'fetch.json',
                   // json will be used if there is no Same Origin Policy violation, otherwise JSONP shall be used
                   dataType: 'json',
                   data: function (term, page) {
                      return {
                         searchkey: term,
                         field: 'Data'
                      };
                   },

                   // This method will be used when the data is returned from the server
                   results: function (data, page) {
                      return {results: data.Datas};
                   },
                },

                // This method will be used when you fetch result from server and add it to the element
                formatResult: formatListOption,

                // This method will be used when you select one of the options
                formatSelection: formatListOptionSelection,

                // This method will be used when you set the value attribute of the element
                initSelection: function(element, callback) {
                   var Datas = jQuery(element).val();
                   Data = []
                   jQuery(Datas.split(",")).each(function () {
                      if (this != "") Data.push (this);
                   });
                   callback (Data);
                },
             });
          });


         <input class="span12" id="Data" name="Data" type="hidden" value="<Value from POST back>" />

No comments: