gpt4 book ai didi

Javascript:从选择输入中获取多个值

转载 作者:行者123 更新时间:2023-11-30 13:49:19 24 4
gpt4 key购买 nike

我有一个选择输入框,它允许我选择多个值。在这种情况下,我有 4 个类别,当我单击一个类别时,会出现子类别。如您所见,它工作得很好。唯一的问题是,当我选择多个类别时,它仅显示第一个所选类别的子类别。选择多个类别时,如何显示每个类别及其子类别?例如,如果我选择类别 1、类别 2 和类别 3,我希望显示以下内容:

类别 1:子类别 1.1、子类别 1.2

类别 2:子类别 2.1、子类别 2.2

类别 3:子类别 3.1、子类别 3.2

    $('select').on('change', function () {
var subcategories = '';
var str = "This category contains these subcategories: ";
var result = str.bold();

switch (this.value) {
case 'Category 1':
subcategories = "Subcategory 1.1, Subcategory 1.2";
break;

case 'Category 2':
subcategories = "Subcategory 2.1, Subcategory 2.2";
break;

case 'Category 3':
subcategories = "Subcategory 3.1, Subcategory 3.2";
break;

case 'Category 4':
subcategories = "Subcategory 4.1, Subcategory 4.2";
break;

}
document.getElementById("showSubcategory").innerHTML = result + subcategories;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple>
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
<option value="Category 4">Category 4</option>
</select>

<div id="showSubcategory"></div>

最佳答案

此功能将为您提供所需的结果。它在选择的选项上使用 Array.reduce 来创建一个字符串,该字符串表示每个选定选项的类别名称和子类别:

$('select').on('change', function() {
var subcategories = Object.values(this.options).reduce((c, v) => {
if (v.selected) {
switch (v.value) {
case 'Category 1':
subcategories = "Subcategory 1.1, Subcategory 1.2";
break;
case 'Category 2':
subcategories = "Subcategory 2.1, Subcategory 2.2";
break;
case 'Category 3':
subcategories = "Subcategory 3.1, Subcategory 3.2";
break;
case 'Category 4':
subcategories = "Subcategory 4.1, Subcategory 4.2";
break;
}
return c + v.value + ': ' + subcategories + '<br>';
}
return c;
}, '');
document.getElementById("showSubcategory").innerHTML = subcategories;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple>
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
<option value="Category 4">Category 4</option>
</select>

<div id="showSubcategory"></div>

关于Javascript:从选择输入中获取多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58587446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com