简体   繁体   English

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

[英]How to change options in child dropdown depending of selected option in parent dropdown with javascript?

So I am working on a dynamic dropdown menu made of a parent and a child as the following: 因此,我正在处理由父母和孩子组成的动态下拉菜单,如下所示:

parent : 父母:

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

Child : 小孩:

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

Here is what I am trying to do: 这是我正在尝试做的事情:

if the selected option has a value of 1 in category_select , then options available in type_select should only have a value of 1 and all other options should disappear. 如果selected选项在category_select的值为1 ,则type_select可用的选项的值应仅为1 ,所有其他选项应消失。

Here is the JS : 这是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 ...
          }
    });
};

How can I display options in the child that only have the same values that the selected option in the parent? 如何在子项中显示仅具有与父项中所选选项相同值的选项?

you can try this script unless hidding but you can disable other options 您可以尝试使用此脚本(除非隐藏),但可以禁用其他选项

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

      }
   };

You can do it in following way: 您可以通过以下方式进行操作:

Like I commented earlier you need to have different child values for each parent value and depending on selected parent you can render child options. 就像我之前评论的那样,每个父级值都需要具有不同的子级值,并且可以根据选定的父级来呈现子级选项。

 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> 

i do not think it is a good idea to have value="1" in the option when you have to set the actual value for the option. 当您必须设置选项的实际值时,我认为在选项中设置value =“ 1”不是一个好主意。 I think we can use display none to hide the value like this 我认为我们可以使用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>

Check out my version on this. 查看我的版本。

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 https://codesandbox.io/s/lpqn3x0zw7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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