Jake S Jake S -4 years ago 128
Javascript Question

Jquery detect bootstrap multiple option dropdown being unselected

I have a dynamic bootstrap multiple drop down selector.

I would like to run some code when a user un-selects a option.

<select id="selectOptions" multiple>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
<option>Test4</option>
<option>Test5</option>
<option>Test6</option>
</select>


I am thinking to do this by jquery however I have an option which already runs on selecting an option, how would I do this when a user clicks to un-select the option.

Thanks

Answer Source

What you can do is to add a change listener to the select element and keep an array of all the items that were selected last time this listener was triggered. This way you can compare the array of items that are currently selected to the array of previously selected items to determine which ones were unselected.

Here is an example:

var prevSelected = [];
$("#selectOptions").change(function(){
  var selected = $(this).val() || [];
  var unselected = prevSelected.filter(function(v){
    return selected.indexOf(v) === -1;
  });
  if(unselected.length){
    console.log("value(s) " + unselected + " were/was unselected");
  }
  prevSelected = selected;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectOptions" multiple>
  <option>Test1</option>
  <option>Test2</option>
  <option>Test3</option>
  <option>Test4</option>
  <option>Test5</option>
 <option>Test6</option>
</select>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download