4
votes

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()
5

5 Answers

4
votes
  $("#player2").select2('data')[0].id;
  $("#player2").select2('data')[0].value;
1
votes
$("#player2").select2('data').text

Using version 3.5.1

0
votes
// this will give you value of selected element.
$("#player2").val(); 
0
votes

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
0
votes
.on("select2:select", function(e) {
    console.log(e.params.data.id);
});