4

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":"someone@gmail.com", "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()
apokryfos
  • 38,771
  • 9
  • 70
  • 114
bo_knows
  • 856
  • 2
  • 9
  • 20

5 Answers5

4
  $("#player2").select2('data')[0].id;
  $("#player2").select2('data')[0].value;
Girish Gupta
  • 1,241
  • 13
  • 27
1
$("#player2").select2('data').text

Using version 3.5.1

Simon
  • 577
  • 6
  • 15
0
// this will give you value of selected element.
$("#player2").val(); 
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
0

I have used form tag and using submit event I have captured id of value.

$("#Selector").submit(function (event) {
  console.log($("#Selector").serialize())
});
//other option is below 
$("#select_machine").select2('data')[0].text
Hardik Gajjar
  • 1,024
  • 12
  • 27
0
.on("select2:select", function(e) {
    console.log(e.params.data.id);
});
fico7489
  • 7,931
  • 7
  • 55
  • 89