coco
coco

Reputation: 15

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.

Here is the 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?

Upvotes: 0

Views: 3227

Answers (4)

Anton Harniakou
Anton Harniakou

Reputation: 880

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

Upvotes: 0

D. Seah
D. Seah

Reputation: 4592

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. I think we can use display none to hide the value like this

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

Upvotes: 0

Sandip Nirmal
Sandip Nirmal

Reputation: 2459

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>

Upvotes: 1

Asif Thebepotra
Asif Thebepotra

Reputation: 340

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

      }
   };

Upvotes: 0

Related Questions