Get Last Selected Value of Select2?

吃可爱长大的小学妹 提交于 2019-12-12 03:47:37

问题


I am using multiple options for Select2 and the data is loaded from a JSON source.

As I'm not sure how to explain it exactly I'll provide an example:

List Options:

  • A
  • B
  • C

If I choose C, then

$("#select2").change(function(){
        alert($(this).val());
    });

Results: [C]

However, If I then choose A I would get [A, C]

If I then choose B I get [A, B, C]

I would preferably want it to append so I would get [C, A, B]. However being able to find the last selected option would be alright. I have tried :last and other answers but nothing seems to work.

Thanks in advance.

My script for Select2:

$.getJSON('profile/Skills.json', function (json) {
        var mainList = [];
        for (var TradeName in json) {
            if (json.hasOwnProperty(TradeName)) {
                var item = json[TradeName];
                mainList.push(item.TradeName);            
            }
        }       
        $(".chyeaSelect").select2({
            data:mainList
        });
    }); 

回答1:


I believe you're looking for something like this:

$.getJSON('https://demo8858242.mockable.io/list', function (json) {
        var mainList = [];
        for (var TradeName in json) {
            if (json.hasOwnProperty(TradeName)) {
                var item = json[TradeName];
                mainList.push(item.TradeName);            
            }
        }       
        $(".select1").select2({
            data:mainList
        });
    }); 

  var array = [];

  $(".select1").change(function(){
    //alert($(this).val());
    array.unshift($(this).val());
    alert(array);
  });

// Alternate
//$(".select1").change(function(){
//    alert($(this).val());
//    //$('.selected').prepend($(this).val());
//});

Codepen




回答2:


I guess it's too late for your problem, but maybe this can help someone else. I use :

$('#select2').on('select2:select', function(e: any) {
    console.log(e.params.data.id);
});

Same with "select2:unselect".



来源:https://stackoverflow.com/questions/37094429/get-last-selected-value-of-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!