Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last selected option from a multiselect?

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.

like image 350
user675 Avatar asked Nov 16 '11 09:11

user675


2 Answers

Something like this

var lastSelected = null;
$('.multiSelectOptions').click(function(){
    lastSelected = this.value;
});
like image 98
Adam Merrifield Avatar answered Nov 15 '22 19:11

Adam Merrifield


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];
    }
});
like image 21
Noumenon Avatar answered Nov 15 '22 18:11

Noumenon