Below is my code for a Select2 box. I need values (tags) already assigned to a record to show initially, this is represented by the AAA
and BBB
values. Then I need to ajax in a list of values to pick from if they want to add new values (tags) to the already existing ones. Everything works except when they select a new value (tag) to add it replaces the existing ones, they disappear. I need them to stay.
<select class="myTags" style="width:100%" multiple="multiple"></select>
<script>
function formatResults(item) {
if (item.loading) return 'Loading...';
return '<div style="font-size:100%;">'+
'<div style="padding:5px;">'+
'<span style="background-color:##e4e4e4; color:##000000; border:1px solid ##aaa; padding:5px;">'+
item.tag+
'</span>'+
'<span style="padding:5px;">'+
' x '+item.popularity+
'</span>'+
'<p style="margin-bottom:0px;">'+
item.description+
'</p>'+
'</div>'+
'</div>';
}
function formatSelection(item) {
return item.tag;
}
jQuery(".myTags").select2({
placeholder: "add a tag, max 20 tags",
maximumSelectionLength: 20,
minimumInputLength: 2,
templateResult: formatResults,
templateSelection: formatSelection,
initSelection: function (element, callback) {
var data = [{ "tag": "AAA", "id": "111" },{ "tag": "BBB", "id": "222" }];
callback(data);
},
escapeMarkup: function (markup) { return markup; }, // let select2's custom formatter work
ajax: {
url: "tags.cfc?method=json_get_valtags",
dataType: 'json',
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: jQuery.map(data, function (item) {
return {
id: item.UNID,
tag: item.TAG,
description: item.DESCRIPTION,
popularity: item.POPULARITY
}
})
};
}
}
});
</script>