Utilizzando this.value
come nella risposta di cui sopra non riesce quando l'utente ha Ctrl + clic e selezionati più elementi - restituisce il valore della prima selezione nella lista, anche se questo non è stato l'ultimo clic. Prova questo:
var previouslySelected = [];
$("#myMultiselect").change (function() {
// Get newly selected elements
var currentlySelected = $(this).val();
var newSelections = currentlySelected.filter(function (element) {
return previouslySelected.indexOf(element) == -1;
});
previouslySelected = currentlySelected;
if (newSelections.length) {
// If there are multiple new selections, we'll take the last in the list
var lastSelected = newSelections.reverse()[0];
}
});
Devi tenere traccia dell'ultimo elemento selezionato da solo. –