Selected option dynamically disables checkbox with same value

Viewed 36

I need a selected option to disable a checkbox with the same value. However, the answers I've found are not dynamic - they reference actual values.

<select name="pickOne" id="pickOne">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>

<checkbox name="pickMulti" value="a">a
<checkbox name="pickMulti" value="b">b
<checkbox name="pickMulti" value="c">c

So if user selected "b" from pickOne, then the checkbox with same value "b" would be deselected and disabled. But this needs to be dynamic without hard-coding any values -- -meaning, if selected value = checkbox value, then disable the checkbox with the same value. Hoping someone can guide me here.

1 Answers

try this

const selectElement = document.getElementById('pickOne');

selectElement.addEventListener('change', (e) => {
   let inputs = document.getElementsByTagName("input")
   for (input of inputs){
   if (input.value===e.target.value) input.disabled = true
   else input.disabled = false   
   }
});
<select name="pickOne" id="pickOne">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>

<input  type="checkbox" name="pickMulti"   value="a"> a
<input type="checkbox" name="pickMulti"  value="b"> b
<input type="checkbox" name="pickMulti"  value="c"> c

Related