1

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

Jake S
  • 122
  • 14

2 Answers2

1

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>
Titus
  • 22,031
  • 1
  • 23
  • 33
0

Per this post you can check for selected values like so

var select = document.getElementById("selectOptions");
$('#selectOptions').change(function(){
    for (index in select){
        if ( $("#selectOptions").val() === "" )
            {
                //some code
            }
    }
});
Community
  • 1
  • 1