JQuery select2 control - select last selected item
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 have to remove another (incompatible) element from the selection. I see two ways to achieve this:
1) disables automatic sorting of the selected values ββ2) get the value of the last selected item and, if necessary, remove the incompatible item from the list
For 1) I could not figure out how to disallow automatic sorting (both "data" and "values" are ordered after making a selection) For 2) I could not find the last selected detail information anywhere (I was expecting to find something in the select variable e ).
My code is as follows:
$("#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);
})
Removing incompatible items works great, but I'm having trouble identifying the last selection the user made.
Any idea how I can accomplish this task? Thank.
source to share
for the second part, this might help you:
$(this).val(); // references the select
you can filter it to get all the values ββyou need.
A Example in fiddle: http://jsfiddle.net/jEADR/1588/
source to share
Hey, maybe I was a little late in answering this, but I found a pretty easy solution. You are correct looking at the event for the last selected item. This worked for me.
var $eventSelect = $('.select_field'); //select your select2 input
$eventSelect.on('select2:unselect', function(e) {
console.log('unselect');
console.log(e.params.data.id); //This will give you the id of the unselected attribute
console.log(e.params.data.text); //This will give you the text of the unselected text
})
$eventSelect.on('select2:select', function(e) {
console.log('select');
console.log(e.params.data.id); //This will give you the id of the selected attribute
console.log(e.params.data.text); //This will give you the text of the selected
})
source to share