Select2 : multi-select : get selected values/text : data array

Retrieve the selected options in an object array. **Need to figure out how to split/format this to get just the text...

by Amit Vishwakarma

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css">
<input type="hidden" id="test" />
<p>Selected IDs: <span id="selectedIDs"></span></p>
<p>Selected Options: <span id="selectedText"></span></p>

CSS

p { margin: 1em 0; }

JavaScript

var test = $('#test');
$(test).select2({
    data:[
    {id:0,text:"enhancement"},
        {id:-1,text:"--select--"},
        {id:0,text:"enhancement"},
        {id:1,text:"bug"},
        {id:2,text:"duplicate"},
        {id:3,text:"invalid"},
        {id:4,text:"wontfix"}
    ],
    multiple: true,
    width: "300px"
});

$(test).change(function() {
    //var ids = $(test).val(); // works
    //var selections = $(test).filter('option:selected').text(); // doesn't work
    //var ids = $(test).select2('data').id; // doesn't work (returns 'undefined')
    //var selections = $(test).select2('data').text; // doesn't work (returns 'undefined')
    //var selections = $(test).select2('data');
    var selections = ( JSON.stringify($(test).select2('data')) );
    //console.log('Selected IDs: ' + ids);
    console.log('Selected options: ' + selections);
    //$('#selectedIDs').text(ids);
    $('#selectedText').text(selections);
});