how to find the latest selected item of a multiple

2019-02-24 11:14发布

I have a <select multiple="multiple" id="multi"> in my website, and I have a script in jquery that has this function:

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

I want to access the latest selected item of the select in this function(the last one selected by user), how can I do that?

6条回答
我命由我不由天
2楼-- · 2019-02-24 11:33

FIDDLE :

Less coding with Optimize solution : Why not use the is function of jquery:

$(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());
    });
});
查看更多
放荡不羁爱自由
3楼-- · 2019-02-24 11:40

How about this

var = last;
$('#multi').find('option').each(function() {
    $(this).click(function() {
        if($(this).hasAttr('selected')) {
            last = $(this);
        }
    }
}
查看更多
等我变得足够好
4楼-- · 2019-02-24 11:45

You can use :selected selector and :last (or alternatively .last()) this way:

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

JSFiddle

查看更多
闹够了就滚
5楼-- · 2019-02-24 11:48

To get the last 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

查看更多
迷人小祖宗
6楼-- · 2019-02-24 11:48

I think you are searching for this

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

DEMO

查看更多
Animai°情兽
7楼-- · 2019-02-24 11:54
var last_value;   

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

define global variable, and every time ur dropdown change the seletion, u can replace the last selected value with the new one.

查看更多
登录 后发表回答