I am using jQuery select2 control and I need to implement the following functionality: if the user tries to add a certain element, based on some algorithm, I should delete another (incompatible) element from the selection. I see two ways to achieve that:
1) inhibit automatic sorting of selected values 2) get value of the last selected item and optionally remove the incompatible item from the list
For 1) I could not figure how to inhibit auto sorting (both "data" and "values" are ordered after a selection is performed) For 2) I could not find last selected item information anywhere (I expected to find something in the select event e variable).
My code is the following:
$("#PhaseFilterSelectedList").select2()
.on("select2:select", function (e) {
// removing option inconsistent with last selected item, if any
var allData = $("#PhaseFilterSelectedList").select2("val");
if (!allData || allData.length < 2)
return;
//alert("Value = " + $("#PhaseFilterSelectedList").select2("val").join(','));
//alert("Data = " + $("#PhaseFilterSelectedList").select2("data")[0].id + " " + $("#PhaseFilterSelectedList").select2("data")[1].id);
var lastItemId = allData.slice(-1)[0];
var lastItemHalf = Math.floor((parseInt(lastItemId) + 1) / 2);
var toRemove = jQuery.grep(allData, function (elem, index) {
return elem != lastItemId && Math.floor((parseInt(elem) + 1) / 2) == lastItemHalf;
});
if (!toRemove || toRemove.length < 1)
return;
allData.splice($.inArray(toRemove[0], allData), 1);
$("#PhaseFilterSelectedList").select2("val", allData);
})
Incompatible element removal works fine, but I have trouble with identifying the last selection performed by the user.
Any idea how can I perform this task? Thank you.