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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…