答案 0 :(得分:2)
循环所有选项时,如果该选项不是所选选项,则需要重新启用它。
const $selects = $(".products-combo");
$selects.on('change', function(evt) {
// create empty array to store the selected values
const selectedValue = [];
// get all selected options and filter them to get only options with value attr (to skip the default options). After that push the values to the array.
$selects.find(':selected').filter(function(idx, el) {
return $(el).attr('value');
}).each(function(idx, el) {
selectedValue.push($(el).attr('value'));
});
// loop all the options
$selects.find('option').each(function(idx, option) {
// if the array contains the current option value otherwise we re-enable it.
if (selectedValue.indexOf($(option).attr('value')) > -1) {
// if the current option is the selected option, we skip it otherwise we disable it.
if ($(option).is(':checked')) {
return;
} else {
$(this).attr('disabled', true);
}
} else {
$(this).attr('disabled', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="products-combo" name="product[]">
<option>Select 1</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
<option value="5">Product 5</option>
</select>
<select class="products-combo" name="product[]">
<option>Select 2</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
<option value="5">Product 5</option>
</select>
<select class="products-combo" name="product[]">
<option>Select 3</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
<option value="5">Product 5</option>
</select>