如何使用javascript在父下拉菜单中根据所选选项更改子下拉菜单中的选项?

时间:2018-08-02 07:02:59

标签: javascript

所以我正在处理一个由父母和孩子组成的动态下拉菜单,如下所示:

父母:

<select id="category_select">
  <option value="1">Electronics</option>
  <option value="2">Appliances</option>
</select>

孩子:

<select id="type_select">
  <option value="1">Phones</option>
  <option value="1">Tablets</option>
  <option value="2">Couch</option>
  <option value="2">Refrigerator</option>
  <option value="2">Vacuum</option>
</select>

这是我想要做的:

如果所选选项在1中的值为category_select,则type_select中可用的选项的值应仅为1,所有其他选项应消失。

这是JS:

    "use strict";
window.onload = function() {
    document.getElementById('category_select').addEventListener("change", function() {
        function parent_() {
            let parent_ = document.getElementById('category_select');
            let ParentVal_ = parent_.options[parent_.selectedIndex].value;
            return ParentVal_; // return parent_ value
        }

        function child_() {
            //something I cant figure out here ...
          }
    });
};

如何在子项中显示与父项中所选选项仅具有相同值的选项?

4 个答案:

答案 0 :(得分:0)

除非隐藏,您可以尝试使用此脚本,但是您可以禁用其他选项

    "use strict";
       window.onload = function() {
       document.getElementById('category_select').addEventListener("change", 
         function() {
            parent_();
         });
       function parent_() {

        let parent_ = document.getElementById('category_select');
        let ParentVal_ = parent_.options[parent_.selectedIndex].value;
        child_(ParentVal_);
        //return ParentVal_; // return parent_ value
    }

    function child_(ParentVal_) {
        let child = document.getElementById('type_select');
        for (var i = 0; i < child.options.length; i++) {
            if (child.options[i].value == ParentVal_) {
                child.options[i].disabled = true;
            }
            else
            {
                child.options[i].enabled = true;
            }
        }

      }
   };

答案 1 :(得分:0)

您可以通过以下方式进行操作:

就像我之前评论的那样,每个父值需要具有不同的子值,并且取决于所选择的父项,您可以呈现子选项。

var childs = {
  Electronics: [
    {
      label: 'Phone',
      value: 1
    },
    {
      label: 'Tablet',
      value: 2
    }
  ],
  Appliances: [
    {
      label: 'Refrigerator',
      value: 1
    },
    {
      label: 'Couch',
      value: 2
    },
    {
      label: 'Vaccum',
      value: 3
    }
  ]
}

function handleChange () {
  var x = document.getElementById("category_select").value;
  
  var childOptions = childs[x]
  var childSelect = document.getElementById('type_select')
  childSelect.innerHTML =''
  
  childOptions.forEach(function (option) {
    var optionEle = document.createElement('option')
    optionEle.value = option.value
    optionEle.label = option.label
    
    childSelect.appendChild(optionEle)
  })
  
}
handleChange()
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  Parent:
  <select id="category_select" onChange='handleChange()'>
    <option value="Electronics">Electronics</option>
    <option value="Appliances">Appliances</option>
  </select>
  <br />

  Child: 
  <select id="type_select"></select>
</body>
</html>

答案 2 :(得分:0)

当您必须设置选项的实际值时,我认为在选项中使用value =“ 1”并不是一个好主意。我认为我们可以使用display none来隐藏这样的值

<head>
<style>
.hide {
  display: none
}
</style>

</head>
<body>

<select id="category_select">
  <option value="1">Electronics</option>
  <option value="2">Appliances</option>
</select>

<select id="type_select">
  <option value="phones" category="1">Phones</option>
  <option value="tablets" category="1">Tablets</option>
  <option value="couch" category="2" class="hide">Couch</option>
  <option value="refrigerator" category="2" class="hide">Refrigerator</option>
  <option value="vacuum" category="2" class="hide">Vacuum</option>
</select>
</body>

<script>
document.getElementById('category_select').addEventListener("change", function() {
  var val = this.value;
  var options = document.getElementById('type_select').options;
  var new_val = null;
  for (var i = 0 ; i < options.length; i++) {
    if (options[i].attributes["category"].value === val) {
      if (!new_val) {
        new_val = options[i].value;
      }
      options[i].classList.remove("hide");
    } else {
      options[i].classList.add("hide");
    }
  }
  document.getElementById('type_select').value = new_val;
});
</script>

答案 3 :(得分:0)

在此查看我的版本。

const categorySelectEl = document.querySelector("#category_select");
const typeSelectEl = document.querySelector("#type_select");

categorySelectEl.addEventListener("change", (e) => {
  renderSelectTypes(typeSelectEl, e.target.value);
});

function renderSelectTypes(el, selectedCategory) {
  const types = [['Phones', 'Tablets'], ['Couch', 'Refrigerator', 'Vacuum']];
  const options = types[Number(selectedCategory) - 1].map(item => `<option value="${selectedCategory}"">${item}</option>`)
  el.innerHTML = options.join("\n");
}

const currentlySelected = categorySelectEl.options[categorySelectEl.selectedIndex].value;

https://codesandbox.io/s/lpqn3x0zw7