on my si...">

How can I find the last selected element of a multiple choice tag using jquery?

I have it <select multiple="multiple" id="multi">

on my site and I have a script in jquery that has this function:

$("#multi").on("change",function(){}) 

      

I want to access the last selected item select

in this function (last selected by the user), how can I do this?

+3


source to share


6 answers


To get the last one selected by the user you can do this

var map = $("#multi").on("change",function(){
    var comp = $("#multi option:selected").map(function() {
            return this.value;
        }).get(),
        set1 = map.filter(function(i) {
            return comp.indexOf(i) < 0;
        }),
        set2 = comp.filter(function(i) {
            return map.indexOf(i) < 0;
        }),
        last = (set1.length ? set1 : set2)[0];

    map = comp;

    // "last" contains the last one selected /unselected

}).find('option:selected').map(function() {return this.value}).get();

      



FIDDLE

+4


source


You can use a selector :selected

and :last

(or alternatively .last()

) like this:

$('#multi').change(function() {
  console.log( $(this).find('option:selected:last').text() );
});

      



JSFiddle

+4


source


I think you are looking for this

$("#multi").on("change",function(){
    alert($("option:selected:last",this).val());    
}) 

      

DEMO

+2


source


var last_value;   

 $('#multi').change(function() {
     last_value = this.val();
alert(last_value);
    });

      

define a global variable and every time ur dropdown changes the seletion you can replace the last selected value with the new one.

+1


source


FIDDLE:

Less coding with Optimize solution: why not use a jQuery function is

:

$(document).ready(function(){
    $('#multi option').click(function(){        
        if($(this).is(':selected'))
            console.log('you have select' + $(this).val());
        else
            console.log('you have Unselect' + $(this).val());
    });
});

      

+1


source


How about this

var = last;
$('#multi').find('option').each(function() {
    $(this).click(function() {
        if($(this).hasAttr('selected')) {
            last = $(this);
        }
    }
}

      

0


source







All Articles