<label>
  <span>Fruit:</span>
  <input type="radio" value="Fruit" checked name="food" id="fruitRad">
</label>
<label>
  <span>Meat:</span>
  <input type="radio" value="Meat" name="food" id="meatRad">
</label>
<label id="fruit">
  <span>Pick Fruit: </span>
  <select id="f-food" name="f-food">
    <option value="1">Apple</option>
    <option value="2">Orange</option>
    <option value="3">Banana</option>
    <option value="4">Peach</option>
  </select>
</label>

<label id="meat" class="hide">
  <span>Pick Meat: </span>
  <select id="m-food" name="m-food">
    <option value="5">Beef</option>
    <option value="6">Chicken</option>
    <option value="7">Fish</option>
    <option value="8">Bacon</option>
  </select>
</label>
label { 
  display: block;
  padding: 0.5em;
}
.hide { display: none ;}
class Iswitch {
  constructor(fDepends) {
    this.data = JSON.parse(fDepends);

    this.switches = [];
    this.depends = [];

    for (const value of this.data.switches) {
      let sw = document.getElementById(value);
      sw.addEventListener("click", this.change.bind(this));
      //sw.addEventListener('click', () => this.change());
      this.switches.push(sw);
    }
    for (const value of this.data.depends) {
      let dep = document.getElementById(value);
      this.depends.push(dep);
    }
  }

  hide(elem) {
    // Hide an element by addign a class
    elem.classList.add("hide");
  }
  show(elem) {
    // Show an element by removing a class
    elem.classList.remove("hide");
  }
  /*
	change () {
        const selected = event.target.id;
        const switches = this.switches;
        const dependInputs = this.depends;
		
        switches.forEach(
            // second parameter is the current index
            (switchElement, currIndex) => {
                if (selected === switchElement.id) {
                    this.show(dependInputs[currIndex]);
                } else {
                    this.hide(dependInputs[currIndex]);
                }
            }
        );*/
  change() {
    const sel = event.target.id;
    for (const [key, value] of this.switches.entries()) {
      // Find the event target switch
      if (sel === value.id) {
        this.show(this.depends[key]); // Show target's dependant input
      } else {
        this.hide(this.depends[key]); // Hide the dependant inputs of all other switches
      }
    }
  }
}

// JSON Data to be changable depending on form
const formSwitch = new Iswitch(
  '{"switches": ["fruitRad", "meatRad"], "depends": ["fruit", "meat"]}'
);
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.