如何仅显示所选选项的文本

Posted

技术标签:

【中文标题】如何仅显示所选选项的文本【英文标题】:How to display only the text of the option selected 【发布时间】:2021-09-24 06:35:42 【问题描述】:

我无法显示我选择的文本。当我检索它的文本时,它会检索我所有选项的文本。

这里的代码(有问题):

 $("#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/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>


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

谢谢

【问题讨论】:

【参考方案1】:

你应该使用$("#productList option:selected").text()

参考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/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

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

【讨论】:

以上是关于如何仅显示所选选项的文本的主要内容,如果未能解决你的问题,请参考以下文章

<select> 仅显示所选选项的第一个字符

使用 jquery 显示基于所选选项的文本框

如何获取所选选项的文本而不是值

在Jquery中获取所选选项的文本值[重复]

jQuery Chosen:如何从多项选择中获取所选选项文本的数组

将输入文本框中的文本替换为所选自动完成选项中的文本