Get last selected value of multiple select element

前端 未结 4 1034
渐次进展
渐次进展 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'));
        }
    });});
    

提交回复
热议问题