Skip to content Skip to sidebar Skip to footer

Get Last Selected Value Of Select2?

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 cho

Solution 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


Solution 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".


Post a Comment for "Get Last Selected Value Of Select2?"