I have four <select>
tags. They are as follows:
<select name="" id="a">
<option value="0">Select</option>
<option value="1">Milk</option>
<option value="2">Eggs</option>
<option value="3">Cheese</option>
<option value="4">Butter</option>
<option value="5">Pizza</option>
</select>
<select name="" id="b">
<option value="0">Select</option>
<option value="1">Milk</option>
<option value="2">Eggs</option>
<option value="3">Cheese</option>
<option value="4">Butter</option>
<option value="5">Pizza</option>
</select>
<select name="" id="c">
<option value="0">Select</option>
<option value="1">Milk</option>
<option value="2">Eggs</option>
<option value="3">Cheese</option>
<option value="4">Butter</option>
<option value="5">Pizza</option>
</select>
<select name="" id="d">
<option value="0">Select</option>
<option value="1">Milk</option>
<option value="2">Eggs</option>
<option value="3">Cheese</option>
<option value="4">Butter</option>
<option value="5">Pizza</option>
</select>
These four are supposed to be having unique selections, although they have the same set of items. So using jQuery, how do I disable the options that are already selected? To be precise, I need to have four values taken from the <select>
tag.
Solution and Problem
The current problem has a solution, but there's a limitation in it. Check my answer for the solution.
This solution is not scalable. If there are four
<select>
s, there should be four variables and the manual process to make them is tedious. Expecting a better solution.
Each time a select changes, just loop over each one, and then disable the option in all other selects where the value matches:
$('select').on('change', function() {
/* enable any previously disabled options */
$('option[disabled]').prop('disabled', false);
/* loop over each select */
$('select').each(function() {
/* for every other select, disable option which matches this this.value */
$('select').not(this).find('option[value="' + this.value + '"]').prop('disabled', true);
});
});