How do i get the selected values from a select 2 that allows multiples


The following code worked until multiple was set to true. I presume it worked before because selected value was a single value whereas now it is an array

<!DOCTYPE html>

        <link href="js/select2.css" rel="stylesheet"/>
        <meta charset="UTF-8">
        <title>Select2 tests</title>

        <script src="js/jquery-1.11.1.min.js"></script>
        <script src="js/select2.js"></script>

<input type='hidden' id='tags' style='width:300px'/>
 <p>Selected IDs: <span id="selectedID"></span></p>
<p>Selected Options: <span id="selectedText"></span></p>       
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} },
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]

$("#tags").change(function() {
    //var theID = $(test).val(); // works
    //var theSelection = $(test).filter(':selected').text(); // doesn't work
    var theID = $("#tags").select2('data').id;
    var theSelection = $("#tags").select2('data').text;

Open in new window

Many thanks
Who is Participating?
GaryConnect With a Mentor Commented:
It gives you an array of the selected values, if you want it as json to post to another page then you do

var selections = JSON.stringify($("#tags").select2('data')))

Open in new window

andiejeAuthor Commented:
merry christmas x
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.