Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.chosen.change() - how to figure out whether it was a select or a deselect action

Tags:

How can we figure out whether a change event triggered on a component was a result of a select or a deselect? How can we grab the value of the selected value only or the deselected value only?

$("#airports-select-2").chosen().change(function(event) {
    console.log('select2 change', event, $(event.target).val());
});

This code gives me all the values that have been selected so far on a multiselect component? How can this be changed to only give me value of the newly selected or deselected component?

like image 824
oneiros Avatar asked Jul 26 '12 21:07

oneiros


2 Answers

From Chosen documentation:

Chosen triggers the standard DOM event whenever a selection is made (it also sends a selected or deselected parameter that tells you which option was changed).

  $('select').on('change', function(event, params) {
    // can now use params.selected and params.deselected
  });
like image 104
Evgeny Avatar answered Sep 21 '22 19:09

Evgeny


On every event fire you can trigger:

var  target = $(event.target),
     priorDataSet = target.data("chosen-values"),
     currentDataSet = target.val();

//Diff and compare the delta here.    

target.data("chosen-values", currentDataSet);

Prior to the update of the data for the DOM element you can diff to determine what the delta is between the value sets. If it's in the old and not in the new it's removed. If it's in the new and not in the old then it's been added.

If you need an example of how to determine the delta between two arrays let me know and I'll whip up an example for that as well.

like image 26
VulgarBinary Avatar answered Sep 24 '22 19:09

VulgarBinary