Select2 : get selected value/text

Use data to retrieve the ID and Text of the selected option.

HTML

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select type="hidden" id="test">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
    <option value="4">four</option>
    <option value="5">five</option>
</select>
<br /><br />
<h2>Accessed with $('#test').select2('data')</h2>
<p>Selected IDs: <span class="highlight" id="selectedID"></span></p>
<p>Selected Options: <span class="highlight" id="selectedText"></span></p>
<hr>
    <h2>Accessed with $('#test').select2('data')<span class="highlight">[0]</span></h2>
<p>Selected IDs: <span class="highlight" id="selectedID0"></span></p>
<p>Selected Options: <span class="highlight" id="selectedText0"></span></p>

CSS

h2 {font-size: 2em; fornt-weight:bold; color: #9f8d04; text-decoration:underline;}
p { margin: 1em 0; }
.highlight {background-color: yellow; font-weight:bold;}

JavaScript

var test = $('#test');
$(test).select2({
    width: "300px",
    tags: true
});

$('#test').on('change', function() {
    var data = $('#test').select2('data');
    var data0 = $('#test').select2('data')[0];
    
    $('#selectedID').text(data.id);
    $('#selectedText').text(data.text);
    
    $('#selectedID0').text(data0.id);
    $('#selectedText0').text(data0.text);
});