Get last selected value of multiple select element

前端 未结 4 998
渐次进展
渐次进展 2021-01-05 01:38

I have a number of select boxes that have been set to accept multiple values. Is there anyway that I can use jQuery to get the last selected value? I\'ve tried using the f

相关标签:
4条回答
  • 2021-01-05 01:57

    yes as @KannanK said, above answers not giving correct value, because it's storing values based on drop down display order, so if select from bottom to top, then will give wrong value.

    I got one better logic to achieve this. on every change of drop down will store into one global variable, so that we can get last selected value in differOpt variable.

    var lastSelectedValues = [];
    $('#yourID').change(function(e) {
        debugger;
        var currentSelVals = $('#yourID').val();
        var differOpt =arr_diff(currentSelVals,lastSelectedValues);
        lastSelectedValues = currentSelVals;
    });
    function arr_diff (a1, a2) {
        var a = [], diff = [];
        for (var i = 0; i < a1.length; i++) {
            a[a1[i]] = true;
        }
        for (var i = 0; i < a2.length; i++) {
            if (a[a2[i]]) {
                delete a[a2[i]];
            } else {
                a[a2[i]] = true;
            }
        }
        for (var k in a) {
            diff.push(k);
        }
        return diff;
    }
    

    Updating one more better solution we can go with onChange option its giving correct value either select/unselect

    $(function () { $('#datadownAutpState').multiselect(
        onChange: function(option, checked) {
            alert(option.val + ' option ' + (checked ? 'selected' : 'deselected'));
        }
    });});
    
    0 讨论(0)
  • 2021-01-05 01:58

    Use the :last selector:

    var latest_value = $("option:selected:last",this).val();
    

    It may be that this in the context of the callback function doesn't refer to the <select> element itself, but instead to an element within it, so try the following:

    var latest_value = 
    $(this).closest('select').find('option').filter(':selected:last').val();
    

    It may also be worth calling console.log(this); inside the callback function, just so you know what element you're actually working with.

    0 讨论(0)
  • 2021-01-05 02:04

    Here is the code to get the latest selected option from multiple select list using Jquery :

    var selected;
    $(document).ready(function() {
    $('#SELECT_ID').on('click', function() {
    var latestSelected;
    if (selected) {
        var currentOptionsValue = $(this).val();
        latestSelected = currentOptionsValue.filter(function(element) {
        return selected.indexOf(element) < 0;
      });
    }
    selected = $(this).val();
    console.log( "latest selected option : " + latestSelected);
    });
    });
    
    0 讨论(0)
  • 2021-01-05 02:11

    Use the last function: like this

    $("#style-list option:selected").last().val()
    
    0 讨论(0)
提交回复
热议问题