I am registering a change event on a multiselect with jQuery to display the selected values in a span element below the multiselect. The change event fires fine when selecting and deselecting elements in the list, except if I deselect the last selected element.
Here is an example (see it in jsfiddle):
<select id="multiselect" multiple>
<optgroup label="Italian">
<option value="CEI2008">CEI2008 — Conferenza Episcopale Italiana (2008)</option>
<option value="LUZZI">LUZZI — Riveduta - Luzzi (1924)</option>
</optgroup>
<optgroup label="Latin">
<option value="NVBSE">NVBSE — Nova Vulgata - Bibliorum Sacrorum Edition (1979)</option>
</optgroup>
</select>
<div>Selected versions: <span id="selectedversions">none</span></div>
and the accompanying jquery code:
$('#multiselect').change(function(){
var selecteditems = $(this).val();
if(selecteditems.length===0){ $('#selectedversions').text('none'); }
else{ $('#selectedversions').text(selecteditems.join(',')); }
});
When the last item is deselected with a CTRL-click, I would expect the change event to fire and jquery val() to return an empty array. Instead it seems that the change event is not firing at all in the case of deselecting the last selected item.
With a bit of debugging I have actually found my own answer.
The change event does fire, but jquery val() returns "null", not an empty array, when no elements are selected. It is enough to compare to null to get it working:
$('#multiselect').change(function(){
var selecteditems = $(this).val();
if(selecteditems===null){ $('#selectedversions').text('none'); }
else{ $('#selectedversions').text(selecteditems.join(',')); }
});