How to get the last selected option from a multiselect?

前端 未结 3 2004
南方客
南方客 2020-12-07 01:09

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

3条回答
  •  一生所求
    2020-12-07 02:02

    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];
        }
    });
    

提交回复
热议问题