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


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

      



+3


source


$("#player2").select2('data').text

      



Using version 3.5.1

+1


source


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

      

0


source


I used a form tag and using the submit event I got the id of the value.

$("#Selector").submit(function (event) {
  console.log($("#Selector").serialize())
});
//other option is below 
$("#select_machine").select2('data')[0].text

      

0


source


.on("select2:select", function(e) {
    console.log(e.params.data.id);
});

      

0


source







All Articles