Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get unselected option from multiple select list

I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?

My sample code is as below.

<select multiple>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
</select> 

I have following jquery code to allow user to select multiple options

$('option').mousedown(function(){ 
    e.preventDefault();
    $(this).prop('selected', $(this).prop('selected') ? false :true);
});
like image 902
Parag Avatar asked Jan 29 '16 20:01

Parag


2 Answers

Mouse events aren't available cross browser

My suggestion would be always store array of previous values on the select.

On every change you can then compare to prior value array and once found update the stored array

$('#myselect').on('change', function() {
  var $sel = $(this),
    val = $(this).val(),
    $opts = $sel.children(),
    prevUnselected = $sel.data('unselected');
  // create array of currently unselected 
  var currUnselected = $opts.not(':selected').map(function() {
    return this.value
  }).get();
  // see if previous data stored
  if (prevUnselected) {
      // create array of removed values        
      var unselected = currUnselected.reduce(function(a, curr) {
        if ($.inArray(curr, prevUnselected) == -1) {
          a.push(curr)
        }
        return a
      }, []);
      // "unselected" is an array
      if(unselected.length){
        alert('Unselected is ' + unselected.join(', '));  
      }

  }
  $sel.data('unselected', currUnselected)
}).change();

DEMO

like image 197
charlietfl Avatar answered Nov 05 '22 16:11

charlietfl


Great question, i wrote some codes for detecting unselected options using data attributes.

$('#select').on('change', function() {  
    var selected = $(this).find('option:selected');
    var unselected = $(this).find('option:not(:selected)');
    selected.attr('data-selected', '1');
    $.each(unselected, function(index, value){
    	if($(this).attr('data-selected') == '1'){
      	    //this option was selected before
            alert("I was selected before " + $(this).val());
            $(this).attr('data-selected', '0');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
 <option data-selected=0 value="volvo">Volvo</option>
 <option data-selected=0 value="saab">Saab</option>
 <option data-selected=0 value="opel">Opel</option>
 <option data-selected=0 value="audi">Audi</option>
</select>
like image 22
Vahid Msm Avatar answered Nov 05 '22 18:11

Vahid Msm