从另一个下拉值的选择中动态填充下拉列表

IT技术 javascript html
2021-02-22 14:12:17

我的要求是,对于“膳食”下拉列表中的选择,第二个下拉列表“类别”应该动态填充与第一个下拉列表中的选择相关的值。然后根据在膳食下拉菜单中选择的内容,列表应在类别中发生变化。我已经编写了以下 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>
3个回答

它可能会帮助你

JSFiddle:演示

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

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

实际上,JavaScript 支持某种循环,即 for...in 循环。

for...in 循环只迭代可枚举的属性。从内置构造函数(如 Array 和 Object)创建的对象从 Object.prototype 和 String.prototype 继承了不可枚举的属性,例如 String 的 indexOf() 方法或 Object 的 toString() 方法。循环将遍历对象本身的所有可枚举属性以及对象从其构造函数的原型继承的属性(更接近原型链中对象的属性覆盖原型的属性)。

在每次迭代中,对象的一个​​属性被分配给变量名,这个循环一直持续到对象的所有属性都用完为止。

更多链接

感谢divy3993!那行得通。但不确定我是否理解它是如何工作的,尤其是“for”循环部分中的 categoryId。你能解释一下流程吗?
2021-05-06 14:12:17
永远没有理由复制选项的文本作为其value值。如果这两个值相同,则永远不要通过声明value.
2021-05-11 14:12:17
你为什么要把这些对象放在另一个?
2021-05-16 14:12:17

您可以使用onchangeevent 并使用 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>

我使用size="5"第二个下拉菜单来查看每个选择的实时结果变化。

附加您的代码的原因是因为在用于清除第二个下拉列表的 for 循环中,不需要更新表达式,因为列表本身的大小正在减小,因此在每次迭代中,列表的长度都会减少,因此您无法清除整个列表。移除函数也应该在 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);
    }
}

}