javascript - 如何根据另一个下拉列表的选择动态地将数组添加到下拉列表中?
问题描述
我有以下代码,它使用数组中包含的项目列表填充下拉列表:
<form id="myGroupSelectForm">
<select id="selectGroup">
<option>Choose a Group</option>
</select>
<select id="selectStudent">
<option>Choose a Student</option>
</select>
</form>
<script type="text/javascript">
var select = document.getElementById("selectGroup");
var options = ["Group 1", "Group 2", "Group 3"];
var i;
for(i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
</script>
我还有 3 个数组,每个数组都包含学生列表。例如:
StudentList1 = ['student1', 'student2'...]
StudentList2 = ['student1', 'student2'...]
StudentList3 = ['student1', 'student2'...]
根据在第一个下拉列表中所做的选择,我将如何使用这 3 个数组中的一个动态填充我的第二个下拉列表?
是否有内置函数可以检查第一个下拉列表中的选择?如果是这样,我该如何捕捉选择?
先感谢您。
解决方案
您可以创建将组映射到其学生列表的映射,然后将change
事件侦听器添加到组选择以附加正确的学生列表。我还将附加代码提取到它自己的函数中以避免代码重复。
var groupSelect = document.getElementById('selectGroup');
var studentSelect = document.getElementById('selectStudent');
var groupOptions = ['Group 1', 'Group 2', 'Group 3'];
var studentList1 = ['group1student1', 'group1student2', 'group1student3'];
var studentList2 = ['group2student1', 'group2student2', 'group2student3'];
var studentList3 = ['group3student1', 'group3student2', 'group3student3'];
// maps groups by name to their corresponding student list
var groupMapping = {
'Group 1': studentList1,
'Group 2': studentList2,
'Group 3': studentList3,
};
// appends an array of options to a given select element
function appendOptions(selectElement, options) {
options.forEach((option) => {
const optionElement = document.createElement('option');
optionElement.textContent = option;
optionElement.value = option;
selectElement.appendChild(optionElement);
});
}
// append group options
appendOptions(groupSelect, groupOptions);
groupSelect.addEventListener('change', (event) => {
// clear student select only keeping the placeholder
studentSelect.options.length = 1;
// append student options using the mapping
appendOptions(studentSelect, groupMapping[event.target.value]);
});
<form id="myGroupSelectForm">
<select id="selectGroup">
<option disabled selected>Choose a Group</option>
</select>
<select id="selectStudent">
<option disabled selected>Choose a Student</option>
</select>
</form>
推荐阅读
- elasticsearch - 如何在弹性搜索索引中搜索值为字段的空数组的文档?
- .htaccess - CakePHP 2.8,url 重写不起作用(只能访问主路由)
- java - 谷歌语音 API 实时识别
- reactjs - 如何重置 Redux 存储中的状态值?
- node.js - 通过 web3 将区块链交易部署到 Kovan 测试网需要比实际使用 web3 更多的资金
- json - VSCode typescript导入json文件高亮问题
- java - 如何使用 Jackson 和 RestTemplate 将 24 小时日期字符串反序列化为 LocalDate
- javascript - FormData array.push 无法发送到 Mongodb & Mongoose CastError: Cast to Array failed for value
- python - Ansible vmware_guest_powerstate 忽略 state_change_timeout
- vb.net - do循环中的vb.net控制台