Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select2 control - retrieve last selected element

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.

like image 525
Alexei - check Codidact Avatar asked Nov 28 '22 23:11

Alexei - check Codidact


1 Answers

Hey I might be a little late answering this but I found a pretty easy solution to this. You we're right by looking through 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
})
like image 117
Oscar Vazquez Avatar answered Dec 01 '22 13:12

Oscar Vazquez