Jquery-select2 getting id and text from select box?
I am using jquery-select2 plugin and I have the following field which is auto-populated 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, like shwon in console.log in the results function, is structured like this: [{"id": " someone@gmail.com ", "text": "someone"}]
Once selected, try console.log ($ ("# player2"). Select2 ("val")) gives me an id, but I can't get the text. None of the following get the text value "someone" in this case, and I can't see where I am going wrong.
$("#player2 option:selected").text()
$("#player2 option:selected").select2().text()
$("#player2").text()
+3
source to share
5 answers