jquery-select2 obtaining ID and text from a select box?

bo_knows picture bo_knows · Nov 10, 2014 · Viewed 7.8k times · Source

I'm using the jquery-select2 plugin, and I have the following field that is being autopopulated by AJAX:

<input type="hidden" id="player2" class="form-control select2">

Here is the javascript:

$('#player2').select2({
    placeholder: "Select an opponent",
    allowClear: false,
    ajax: {
        dataType: "json",
        url: "getUsers.php",
        data: function (term) {
            return {
                q: term, // search term
            };
        },
        results: function (data) {
            console.log(data);
            return {results: data};
        },

    }
}); 
console.log($("#player2").select2("val"));

The data, as shwon in the console.log within the results function, is structured like this: [{"id":"[email protected]", "text":"someone"}]

After the choice is selected, trying to console.log($("#player2").select2("val")) gives me the ID, but I can't seem to get the text. None of the following works to get the text value of "someone" in this case and I don't see where I'm going wrong.

$("#player2 option:selected").text()
$("#player2 option:selected").select2().text()
$("#player2").text()

Answer

Girish Gupta picture Girish Gupta · Sep 3, 2015
  $("#player2").select2('data')[0].id;
  $("#player2").select2('data')[0].value;