我的要求是,對於「用餐」下拉列表中的選擇,第二個下拉列表「類別」應該動態填充與選擇相關的值首先下拉列表。然後根據用餐下拉菜單中選擇的內容,列表應該在類別中更改。我寫了下面的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>
的可能重複[如何清除在下拉框中的所有選項?(http://stackoverflow.com/questions/3364493/how-do-i-clear-all-選項在下拉框) – psycotik
看看我的編輯,你只需要使用switch語句。 –