Let's say I have three dropdown lists...
<select name="list-01">
<option value="1">Option 001</option>
<option value="2">Option 002</option>
<option value="3">Option 003</option>
</select>
<select name="list-02">
<option value="1">Option 001</option>
<option value="2">Option 002</option>
<option value="3">Option 003</option>
</select>
<select name="list-03">
<option value="1">Option 001</option>
<option value="2">Option 002</option>
<option value="3">Option 003</option>
</select>
...how do I prevent a user from choosing Option 003, for all three selections?
All three can be Option 001 or Option 002. Any two can be Option 003, but as soon as you tried to select that for the third dropdown list, it would - for this example - give you an alert that you cannot choose that option for all three.
I'm also looking for this to be flexible enough that, if there were twelve dropdown lists, you would only be able to choose Option 003 for eleven of them.
I will assume the HTML as the state of the app and no other state representations (although it applies the same logic)
that's basically the algorithm. we can optimize it by early exits.
But maybe I missunderstood something.
Michael Richins
Full-Stack Designer
Here is my solution. hopefully, it's self-explanatory. I've created a class that accepts three parameters; a node list of select elements, the excluded option value, and a max number of occurrences.
var selects = document.querySelectorAll('[js-select]'); var optionCheck = new OptionCheck(selects, 'Ppl', 2);At startup and after every change event, I set values and then check values. If there are as many selected options as there are the max number of occurrences, then the other select's option is disabled.