Skip to content
Advertisement

toggle (enable/disable) between two divs in user form

I’m new in JavaScript (not familiar yet with jquery) and I’m trying to insert some logic into my form.

I want to be able to give the user the option to choose between two options (in my example: option_1 OR option_2) and soon the user insert some text to option_1 I want all sub-options in option_2 to become disabled, and if he decides to delete the text he wrote in option_1, option_2 needs to become enable again, and vice versa with writing text in any sub-option in option_2 first (option_1 needs to become disable).

<div id=options>
    <div id ="option_1">
     <input type="text"/>
    </div>

    <div id="option_2">
      <input id="option_2_a" type="text"/>
      <input id="option_2_b" type="text"/>
      <input id="option_2_c" type="text"/>
    </div>
 </div>

I’m sorry I do not have any js code to show because so far I’m so confused that my peace of code will only make it hard for you to assist me ^.^

Thanks in advance!

Advertisement

Answer

You can use fieldset html tag like this:

const o1 = document.getElementById("option_1");
const o2 = document.getElementById("option_2");
var o2Values = {};

o1.childNodes.forEach((o) =>
  o.addEventListener("input", (e) => (o2.disabled = e.target.value))
);
o2.childNodes.forEach((o) => {
  o.addEventListener("input", (e) => {
    o2Values[e.target.id] = e.target.value;
    o1.disabled = Object.values(o2Values).some((v) => v);
  });
});
<div id="options">
  <fieldset id="option_1">
    <input type="text" id="o1_a" />
  </fieldset>
  <br />
  <fieldset id="option_2">
    <input id="o2_a" type="text" />
    <input id="o2_b" type="text" />
    <input id="o2_c" type="text" />
  </fieldset>
</div>
Advertisement