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.
initSelection
option – Swaneecallback(JSON.parse(elementText));
– Swaneedata-initvalue
withvalue
and usecallback(JSON.parse(elementText));
ininitSelection
. – Supremacyvar elementText = JSON.parse($(element).val());
instead of changing the callback. You didn't put your suggestion as answer, so I can't mark your answer as accepted one but I have upvoted it. – Parturition