A very weird way for passing data. I prefer to get a JSON string/object from server and then assign values and stuff.
Anyway, when you do this var elementText = $(element).attr('data-initvalue');
you're getting this [{"id":"IN","name":"India"}]
. That result you must PARSE it as suggested above so you can get the real vales for id ("IN") and name("India"). Now there are two scenarios, multi-select & single-value Select2.
Single Values:
$(element).select2({
initSelection : function (element, callback) {
var data = {id: "IN", text: "INDIA"};
callback(data);
}//Then the rest of your configurations (e.g.: ajax, allowClear, etc.)
});
Multi-Select
$("#tags").select2({
initSelection : function (element, callback) {
var countryId = "IN"; //Your values that somehow you parsed them
var countryText = "INDIA";
var data = [];//Array
data.push({id: countryId, text: countryText});//Push values to data array
callback(data); //Fill'em
}
});
NOW HERE'S THE TRICK! Like belov91 suggested, you MUST put this...
$(element).select2("val", []);
Even if it's a single or multi-valued Select2. On the other hand remember that you can't assign the Select2 ajax function to a <select>
tag, it must be an <input>
.
Hope that helped you (or someone).
Bye.