I'm looking for a way to get the last user-selected option in a multiselect form using jQuery.
I'm not looking for the last item on the list, but for the last item the user clicked.
Something like this
var lastSelected = null;
$('.multiSelectOptions').click(function(){
lastSelected = this.value;
});
Using this.value
as in the answer above fails when the user has Ctrl+clicked and selected multiple items -- it returns the value of the first selection in the list, even if that was not the last clicked. Try this:
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];
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With