sfarzoso
sfarzoso

Reputation: 1600

How to get value of deselected option?

Suppose I have a select like this:

<select id="cars" multiple>
  <option value="1">Ferrari</option>
  <option value="2">Lamborghini</option>
</select>

Imagine now that both values are selected, I deselect Ferrari, how can I retrieve the value of the deselected option, so in this case Ferrari?

I tried with:

$('#cars option').on('click', function(){
    console.log($(this).val());
});

but the event is never fired, I also tried with change, this is fired, but I get only the selected values not the deselected one.

Upvotes: 0

Views: 257

Answers (1)

Taplar
Taplar

Reputation: 24965

You could incorporate the usage of a class to track on change which elements are selected, and inversely which ones are no longer selected.

var $cars = $('#cars').on('change', function(){
  // find the options that were selected, but are not now
  var $deselected = $cars.find('option.selected:not(:checked)');
  
  // add the selected class to the selected options for tracking
  $cars.find('option:checked').addClass('selected');
  // remove the selected class to untrack them
  $deselected.removeClass('selected');
  
  // report which options were deselected
  console.log($deselected.get());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="cars" multiple>
  <option value="1">Ferrari</option>
  <option value="2">Lamborghini</option>
</select>

Upvotes: 2

Related Questions