how to find the latest selected item of a multiple select tag using jquery?

后端 未结 6 1100
孤街浪徒
孤街浪徒 2021-01-20 15:48

I have a

提交评论

  • 2021-01-20 16:04

    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());
        });
    });
    
    0 讨论(0)
  • 2021-01-20 16:07

    How about this

    var = last;
    $('#multi').find('option').each(function() {
        $(this).click(function() {
            if($(this).hasAttr('selected')) {
                last = $(this);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-20 16:14
    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.

    0 讨论(0)
  • 2021-01-20 16:21

    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

    0 讨论(0)
  • 2021-01-20 16:22

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

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

    JSFiddle

    0 讨论(0)
  • 提交回复
    热议问题