JSFiddle - React, Tailwind, and code Playground
HTML
<SELECT id="topo" NAME="topo" MULTIPLE size="5"> <OPTION VALUE="mushrooms">mushrooms</option> <OPTION VALUE="greenpeppers">green peppers <OPTION VALUE="onions">onions </option> <OPTION VALUE="tomatoes">tomatoes </option> <OPTION VALUE="olives">olives</option> </SELECT><button>Clear Log</button>
<div id="log"></div>
JavaScript
var $topo = $('#topo')
var valArray = ($topo.val()) ? $topo.val() : [];
$topo.change(function() {
var val = $(this).val(),
numVals = (val) ? val.length : 0,
changes;
if (numVals != valArray.length) {
var longerSet, shortSet;
(numVals > valArray.length) ? longerSet = val : longerSet = valArray;
(numVals > valArray.length) ? shortSet = valArray : shortSet = val;
//create array of values that changed - either added or removed
changes = $.grep(longerSet, function(n) {
return $.inArray(n, shortSet) == -1;
});
logChanges(changes, (numVals > valArray.length) ? 'selected' : 'removed');
}else{
// if change event occurs and previous array length same as new value array : items are removed and added at same time
logChanges( valArray, 'removed');
logChanges( val, 'selected');
}
valArray = (val) ? val : [];
});
function logChanges(array, type) {
$.each(array, function(i, item) {
$('#log').append(item + ' was ' + type + '<br>');
});
}
$('button').click(function() {
$('#log').empty()
});