as already mentioned, when I select an option of a select I want the others to have an empty value if one is already selected, i.e. I want the others to have a value="" (therefore that it be emptied"
this is my code:
let selects = document.querySelectorAll('.selectes')
selects.forEach(sel =>
sel.addEventListener('change', function (e) {
if (e.target.id != sel.getAttribute('id')) {
sel.value = '';
}
})
)
<label for="cars">Choose a car:</label>
<select name="cars" id="cars" class="selectes">
<option value="">Value Empty</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<label for="cars">Choose a cycle:</label>
<select name="cars" id="cycles" class="selectes">
<option value="">Value Empty</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<label for="cars">Choose a bike:</label>
<select name="cars" id="bikes" class="selectes">
<option value="">Value Empty</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
3
Answers
Get all the
select
elements, add listener to each select element by looping over them. So whenever a select change, loop through all otherselect
elements and set their values into "Value Empty".You need to loop through all the selects within the listener, and reset the ones that aren’t the one that was just changed.
Maybe you can do that this way ?
First of all, the
forEach()
method accepts up to 3 arguments: link on the docsel
-> the current elementi
-> current element list indexAll
-> a return on the entire processed listLike any selection made on a list, this acts on the
selectedIndex
property;this code here uses this property exclusively.
as any change to one of the
select
s implies an update of the otherselect
s, they must be reset theirselectedIndex
to zero in an internal loop of theAll
argument, this time withx
as loop index.if
x===i
, then we are on the same element, it is therefore excluded to reset its selectedIndex property to zero.