Select2 : get selected value/text

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

by Sree K

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>
    <footer>
        <div>Based on <a href="http://stackoverflow.com/q/19814601">this SO question</a></div>
        <div>Added as a comment to <a href="http://stackoverflow.com/a/19814656/1369473">this answer</a></div>
    </footer>

CSS

h2 {font-size: 2em; fornt-weight:bold; color: #9f8d04; text-decoration:underline;}
p { margin: 1em 0; }
.highlight {background-color: yellow; font-weight:bold;}
footer { width:100%; bottom: 2px; position: fixed; padding: 5px; background-color: #ddd }

JavaScript

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

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