简体   繁体   English

通过选择另一个下拉值动态填充下拉列表

[英]Dynamically Populating Drop down list from selection of another drop down value

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. 我已经编写了以下Javascript函数,但我得到的输出不是新鲜填充的第二个下拉列表。 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>

It might help you 可能对您有帮助

JSFiddle : DEMO JSFiddle:演示

HTML 的HTML

<select name="meal" id="meal" onChange="changecat(this.value);">
    <option value="" disabled selected>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="" disabled selected>Select</option>
</select>

JS JS

var mealsByCategory = {
    A: ["Soup", "Juice", "Tea", "Others"],
    B: ["Soup", "Juice", "Water", "Others"],
    C: ["Soup", "Juice", "Coffee", "Tea", "Others"]
}

    function changecat(value) {
        if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
        else {
            var catOptions = "";
            for (categoryId in mealsByCategory[value]) {
                catOptions += "<option>" + mealsByCategory[value][categoryId] + "</option>";
            }
            document.getElementById("category").innerHTML = catOptions;
        }
    }

Actually there is kind of loop supported by JavaScript ie for...in loop. 实际上,JavaScript支持某种循环,即for ... in循环。

A for...in loop only iterates over enumerable properties. for ... in循环仅迭代可枚举的属性。 Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Object.prototype and String.prototype, such as String's indexOf() method or Object's toString() method. 从内置构造函数(如Array和Object)创建的对象继承了Object.prototype和String.prototype的不可枚举的属性,例如String的indexOf()方法或Object的toString()方法。 The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties). 循环将遍历对象本身的所有可枚举属性,以及对象从其构造函数的原型继承的那些属性(在原型链中更靠近对象的属性将覆盖原型的属性)。

In each iteration one property from object is assigned to variable-name and this loop continues till all the properties of the object are exhausted. 在每次迭代中,将来自对象的一个​​属性分配给变量名,并且此循环持续进行到对象的所有属性用尽为止。

For more Link 有关更多链接

You can use onchange event and use a switch statement with the selected value from the first dropdown and according to it append the options to the second list: 您可以使用onchange事件,并使用带有从第一个下拉列表中选择的值的switch语句,并根据该语句将选项追加到第二个列表中:

  var A= ["Soup", "Juice", "Tea","Others"]; var B= ["Soup","Juice","Water", "Others"]; var C= ["Soup","Juice","Coffee", "Tea","Others"]; var changeCat = function changeCat(firstList) { var newSel = document.getElementById("category"); //if you want to remove this default option use newSel.innerHTML="" newSel.innerHTML="<option value=\\"\\">Select</option>"; // to reset the second list everytime var opt; //test according to the selected value switch (firstList.options[firstList.selectedIndex].value) { case "A": for (var i=0; len=A.length, i<len; i++) { opt = document.createElement("option"); opt.value = A[i]; opt.text = A[i]; newSel.appendChild(opt); } break; case "B": for (var i=0; len=B.length, i<len; i++) { opt = document.createElement("option"); opt.value = B[i]; opt.text = B[i]; newSel.appendChild(opt); } break; case "C": for (var i=0; len=C.length, i<len; i++) { opt = document.createElement("option"); opt.value = C[i]; opt.text = C[i]; newSel.appendChild(opt); } break; } } 
 <select name="meal" id="meal" onchange="changeCat(this);"> <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" size="5"> <option value="">Select</option> </select> 

I used size="5" with the second dropdown to see the live result changes for each selection. 我在第二个下拉菜单中使用了size="5"来查看每个选择的实时结果更改。

The reason why your code gets appended is because in the for loop for clearing the second drop down list, the update expression is not required as the list is itself being reduced in size and so in every iteration the length of the list decreases, and so you are unable to clear the whole list. 附加代码的原因是因为在用于清除第二个下拉列表的for循环中,不需要更新表达式,因为列表本身会减小大小,因此在每次迭代中列表的长度都会减小,因此您无法清除整个列表。 Also the removal function should be outside the if conditions to avoid redundancy.`function changecat() { var selectHTML = ""; 同样,删除功能应在if条件之外,以避免冗余。function changecat(){var selectHTML =“”;

var A = ["Soup", "Juice", "Tea", "Others"];
var B = ["Soup", "Juice", "Water", "Others"];
var C = ["Soup", "Juice", "Coffee", "Tea", "Others"];
var select = document.getElementById('category').options.length;

    for (var i = 0; i < select; ) {
        document.getElementById('category').options.remove(i);
    }

if (document.getElementById("meal").value == "A") {


    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") {

    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") {

    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);
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM