且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在另一个下拉列表中选择的相同值自动填充一个下拉列表中的值?

更新时间:2022-12-02 11:51:08

这是一个onchange事件侦听器,用于演示该想法.因此,要查看实际效果,您需要更改选择.我通过字典和循环来实现目标.

This is an onchange event listener to demonstrate the idea. So to see it in action, you need to change the selection. I accomplish the goal via dictionaries and loops.

//plastic cups can have coffee or tea
//glass cups can have Iced Coffee, Iced Tea, or Soda
//and we don't need to include anything here for no cup selected
cups = {"plastic": ["Coffee", "Tea"], "glass": ["Iced Coffee", "Iced Tea", "Soda"]}

//get the selection box for cups
cup = document.getElementById("Cup");
//add an event listener
cup.addEventListener("change", function() {

  //get the selection box for drinks
  drink = document.getElementById("Drink")
  //set its innerHTML to be nothing
  drink.innerHTML = "";
  //if the value from the cups selection box is not nocup (no cup selected)
  if (cup.value != "nocup")
  {
    //loop over the different drinks
    for(var i = 0; i < cups[cup.value].length; i++)
    {
      //and add them to the drink options drop down
      drink.innerHTML += "<option>" + cups[cup.value][i] + "</option>";
    }
  }
  //otherwise, if the cups selection box is "nocup" (no cup is actually selected)
  else
  {
    //set the drinks selection box back to "No cup selected"
    drink.innerHTML = "<option>No cup selected</option>"
  }

});

<select id="Cup">
  <option value="nocup">
    Select one
  </option>
  <option value="plastic">
    Plastic
  </option>
  <option value="glass">
    Glass
  </option>
</select>

<select id="Drink">
  <option>
    No cup selected
  </option>
</select>