Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiselect Detect Option Selected and Deselected On Change

I want to check the if the changed state of a multiselect is deselect or select.

pseudo-code:

$(document).on('change', '.mySelect', function (event) {
        if(event === 'selected'){
            alert("You have selected this item.");
        } else {
            alert("You have deselected this item.");
        }
});

Something like this doesn't work. How can i check weather the event was a "select" event or a "deselect" event?

EDIT

Here is a jsfiddle DEMO

like image 411
Roger Avatar asked Oct 21 '25 11:10

Roger


1 Answers

Try saving the current state of the select element on change:

http://jsfiddle.net/Wexcode/a4mf8akj/5/

function wasDeselected (sel, val) {
  if (!val) {
    return true;      
  }
  return sel && sel.some(function(d) { return val.indexOf(d) == -1; })
}

$(document).on('change', 'select', function (event) {
  var message,
      $select = $(event.target),
      val     = $select.val(),
      sel     = $('select').data('selected');

  // Store the array of selected elements
  $select.data('selected', val);

  // Check the previous and current val
  if ( wasDeselected(sel, val) ) {
    message = "You have deselected this item.";
  } else {
    message = "You have selected this item.";
  }
  alert(message);
});
like image 126
Wex Avatar answered Oct 23 '25 00:10

Wex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!