如何仅显示所选选项的文本
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>
【讨论】:
以上是关于如何仅显示所选选项的文本的主要内容,如果未能解决你的问题,请参考以下文章