简体   繁体   中英

How to Populate the 3rd Dropdown in HTML Javascript?

I'm having a problem not knowing how to populate or create the 3rd box that will show the result on the 2nd box. What I'm trying to do is select the brand, then model then on 3rd box, it will show their model numbers.

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

and here's the other code

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

If you want to save the model number with the device, I'd suggest you to use array of objects and add the model number as value to second drop down as shown below.

And from second dropdown, you can get the value and then display it wherever you want.

 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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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