How to display only the text of the option selected

I have a problem to display the text of what I’ve selected. When I retrieve the text of it, it retrieve me the text of all the option.

Here the code (with the problem):

 $("#productList").select2();
 $(document).ready(function(){
 let data = [{"reference":'BC-ENFANT',"name":'Pour les Enfants',"description":'Soins pour les enfants...',"id":155,"productList":[{"id":13655,"reference":'PROD_ENFANT_01',"name":'Brushing'},{"id":13656,"reference":'PROD_ENFANT_03',"name":'Soins'},]},{"reference":'BC-FEMME',"name":'Pour les Femmes',"description":'Prestations pour les femmes',"id":154,"productList":[{"id":13657,"reference":'PROD_ENFANT_01',"name":'Brushing'},{"id":13658,"reference":'PROD_ENFANT_03',"name":'Soins'}]}];

let results = data.map(group => ({
  text: group.name,
  children: group.productList.map(product => ({
    id: product.id,
    text: product.name
  }))
}));
  $('#productList').select2({
                multiple: false,
                data: results,
                minimumResultsForSearch: -1,
            });
 console.log($('#productList').text());
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>


        <label>Prestation</label>
           <select id="productList"></select>
  

Thank you

Answer

You should use $("#productList option:selected").text().

Ref.How do I get the text value of a selected option in Jquery?

$("#productList").select2();
$(document).ready(function () {
  let data = [ { reference: "BC-ENFANT", name: "Pour les Enfants", description: "Soins pour les enfants...", id: 155, productList: [ { id: 13655, reference: "PROD_ENFANT_01", name: "Brushing" }, { id: 13656, reference: "PROD_ENFANT_03", name: "Soins" }, ], }, { reference: "BC-FEMME", name: "Pour les Femmes", description: "Prestations pour les femmes", id: 154, productList: [ { id: 13657, reference: "PROD_ENFANT_01", name: "Brushing" }, { id: 13658, reference: "PROD_ENFANT_03", name: "Soins" }, ], }, ];

  let results = data.map(group => ({
    text: group.name,
    children: group.productList.map(product => ({
      id: product.id,
      text: product.name,
    })),
  }));
  $("#productList").select2({
    multiple: false,
    data: results,
    minimumResultsForSearch: -1,
  });
  console.log($("#productList option:selected").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<label>Prestation</label>
<select id="productList"></select>