我的要求是,对于“膳食”下拉列表中的选择,第二个下拉列表“类别”应该动态填充与第一个下拉列表中的选择相关的值。然后根据在膳食下拉菜单中选择的内容,列表应在类别中发生变化。我已经编写了以下 Javascript 函数,但我得到的输出不是新鲜填充第二个下拉列表。更改选择后,新列表将附加到旧列表中。
function changecat() {
var selectHTML = "";
var A = ["Soup", "Juice", "Tea", "Others"];
var B = ["Soup", "Juice", "Water", "Others"];
var C = ["Soup", "Juice", "Coffee", "Tea", "Others"];
if (document.getElementById("meal").value == "A") {
var select = document.getElementById('category').options.length;
for (var i = 0; i < select; i++) {
document.getElementById('category').options.remove(i);
}
for (var i = 0; i < A.length; i++) {
var newSelect = document.createElement('option');
selectHTML = "<option value='" + A[i] + "'>" + A[i] + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('category').add(newSelect);
}
}
else if (document.getElementById("meal").value == "B") {
var select = document.getElementById('category').options.length;
for (var i = 0; i < select; i++) {
document.getElementById('category').options.remove(i);
}
for (var i = 0; i < B.length; i++) {
var newSelect = document.createElement('option');
selectHTML = "<option value='" + B[i] + "'>" + B[i] + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('category').add(newSelect);
}
}
else if (document.getElementById("project").value == "C") {
var select = document.getElementById('category').options.length;
for (var i = 0; i < select; i++) {
document.getElementById('category').options.remove(i);
}
for (var i = 0; i < C.length; i++) {
var newSelect = document.createElement('option');
selectHTML = "<option value='" + C[i] + "'>" + C[i] + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('category').add(newSelect);
}
}
}
HTML-
<select name="meal" id="meal" onchange="changecat();">
<option value="">Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select name="category" id="category">
<option value="">Select</option>
</select>