我遇到一个问题,不知道如何填充或创建第三个框,该框将在第二个框上显示结果。我想做的是选择品牌,然后在第三个方框中选择型号,它将显示其型号。

<select name="device" id="device" onchange="changecat(this.value);">
  <option value="" disabled selected>Select</option>
  <option value="A">Apple</option>
  <option value="S">Samsung</option>
  <option value="L">LG</option>
  <option value="G">Google</option>
  </select>
  <select name="category" id="category">
    <option value="" disabled selected>Select</option>
  </select>


这是其他代码

var brandByCategory = {
  A: ["iPhone", "iPhone 3G", "iPhone 3GS", "iPhone 4"],
  S: ["Galaxy S3", "Galaxy S4", "Galaxy S5", "Galaxy S6"],
  L: ["G3", "G4", "G5", "G6", "G7"],
  G: ["Pixel", "Pixel XL", "Pixel 2", "Pixel 2 XL", "Pixel 3", "Pixel 3 XL", "Pixel 3A", "Pixel 3A XL", "Pixel 4", "Pixel 4 XL"]

}

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

最佳答案

如果要与设备一起保存型号,建议您使用对象数组,并将型号作为值添加到第二个下拉列表中,如下所示。

从第二个下拉菜单中,您可以获取该值,然后将其显示在任意位置。



var brandByCategory = {
    A: [{
        name: "iPhone",
        model: "10"
    }, {
        name: "iPhone 3G",
        model: "3G"
    }],
    S: [{
        name: "Galaxy S3",
        model: "S3"
    }, {
        name: "Galaxy S4",
        model: "S4"
    }]

}

function changecat(value) {
    if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
    else {
        var catOptions = "";
        for (categoryId in brandByCategory[value]) {
            catOptions += `<option value = "${brandByCategory[value][categoryId].model}">${brandByCategory[value][categoryId].name}</option>`;
        }
        document.getElementById("category").innerHTML = catOptions;
    }
}
var input = document.getElementById("modelNumber")

function populateValue(val) {
    input.value = val;
}

<select name="device" id="device" onchange="changecat(this.value);">
    <option value="" disabled selected>Select</option>
    <option value="A">Apple</option>
    <option value="S">Samsung</option>
</select>
<select name="category" id="category" onchange="populateValue(this.value);">
    <option value="" disabled selected>Select</option>
</select>

<input type="text" id="modelNumber" />

关于javascript - 如何在HTML Javascript中填充第3个下拉列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59622537/

10-09 13:46