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).
JavaScript
x
12
12
1
<div id=options>
2
<div id ="option_1">
3
<input type="text"/>
4
</div>
5
6
<div id="option_2">
7
<input id="option_2_a" type="text"/>
8
<input id="option_2_b" type="text"/>
9
<input id="option_2_c" type="text"/>
10
</div>
11
</div>
12
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:
JavaScript
1
13
13
1
const o1 = document.getElementById("option_1");
2
const o2 = document.getElementById("option_2");
3
var o2Values = {};
4
5
o1.childNodes.forEach((o) =>
6
o.addEventListener("input", (e) => (o2.disabled = e.target.value))
7
);
8
o2.childNodes.forEach((o) => {
9
o.addEventListener("input", (e) => {
10
o2Values[e.target.id] = e.target.value;
11
o1.disabled = Object.values(o2Values).some((v) => v);
12
});
13
});
JavaScript
1
11
11
1
<div id="options">
2
<fieldset id="option_1">
3
<input type="text" id="o1_a" />
4
</fieldset>
5
<br />
6
<fieldset id="option_2">
7
<input id="o2_a" type="text" />
8
<input id="o2_b" type="text" />
9
<input id="o2_c" type="text" />
10
</fieldset>
11
</div>