My requirement is that for a selection in a 'meal' drop down list, a second drop down list 'category' should get dynamically populated with values related to the selection in first drop down list. Then depending on what is selected in the meal dropdown, the list should change in category. I have written the following Javascript function but the output I'm getting is not freshly populating the 2nd dropdown. On change of a selection, the new list is just getting appended to the old list.
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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…