首页 > 解决方案 > 如何根据另一个下拉列表的选择动态地将数组添加到下拉列表中?

问题描述

我有以下代码,它使用数组中包含的项目列表填充下拉列表:

<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 个数组中的一个动态填充我的第二个下拉列表?

是否有内置函数可以检查第一个下拉列表中的选择?如果是这样,我该如何捕捉选择?

先感谢您。

标签: javascript

解决方案


您可以创建将组映射到其学生列表的映射,然后将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>


推荐阅读