Setting initial values on load with Select2 with Ajax

Ravi picture Ravi · Sep 9, 2013 · Viewed 113.5k times · Source

I have select2 controls set up with Ajax (have both single and multiple). I'm trying to have some values on page load but I'm not able to get this to work however. My code for select2 is given below:

function AjaxCombo(element, url, multival ){  // multival = true or false
  multival = multival || false;
  $(element).select2({
   minimumInputLength: 2,
   multiple: multival,
   separator: '|',
   ajax: {
     url: url,
     dataType: 'json',
     data: function (term, page) {
        var targetname = $(this).attr('name');
        var target = targetname.slice(targetname.indexOf("[")+1, targetname.indexOf("]"));
       return {
         targettype: "search",
         target: target,
         search: term
       };
     },
     results: function (data, page) {
       return { results: data };
     }
   }
 });
}
AjaxCombo(".ajaxselect", "includes/linkedcontrol.php", false);
AjaxCombo(".ajaxmultiselect", "includes/linkedcontrol.php", true);

The Ajax combo works fine, am having trouble only with the initial values load. I tried this code below but couldn't get it to work:

initSelection : function (element, callback) {
    var elementText = $(element).attr('data-initvalue');
    callback(elementText);
}

My HTML from php is returned as below :

<input name='header[country]' class='ajaxselect'  data-initvalue='[{"id":"IN","name":"India"}]' data-placeholder='Select Country' value='' />

I see that values are populated from php, only my jquery is having issues. My values in the control show up as US | United States of America. I guess I have edited the select2 source for getting this format as default without using format option.

Can anyone please help me populate the default values? Thanks in advance.

EDIT: This question pertains to Select2 version <4.0. This option is removed from v4.0 and is much simpler now.

Answer

JD - DC TECH picture JD - DC TECH · Jan 16, 2014

Maybe this work for you!! This works for me...

initSelection: function (element, callback) {

            callback({ id: 1, text: 'Text' });
}

Check very well that code is correctly spelled, my issue was in the initSelection, I had initselection