最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiselect Detect Option Selected and Deselected On Change - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited May 4, 2017 at 2:04 Roger asked Dec 19, 2014 at 22:36 RogerRoger 3,2561 gold badge25 silver badges38 bronze badges 2
  • Is the element with the class .mySelect a checkbox? – ateich Commented Dec 19, 2014 at 22:38
  • 1 Please provide the name/link of the plugin you are using or a jsfiddle and the html code – Sam Battat Commented Dec 19, 2014 at 22:45
Add a ment  | 

2 Answers 2

Reset to default 4

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

http://jsfiddle/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);
});

The trick is to track the selected options length ..

var $select = $('select');
$select.change(function () {
    // Last saved state;
    var lastState = $(this).data('total'),
         // New state;
        changedState = $(this).find('option:selected').length,

        txt = (lastState < changedState ?
            'selected' : (
        lastState > changedState ?
            'Deselected' :
            'Only one option is selected'));
    // save state
    $(this).data('total', changedState);
    $('#console').append('<p>' + lastState + ' => ' + changedState + '<span>' + txt + '</span></p>');

// Initializing tracker
}).data('total', $select.find('option:selected').length);

Try this here

发布评论

评论列表(0)

  1. 暂无评论