唯一选择选项值 [英] Unique Select option values
问题描述
我有3条select语句,每条语句都具有相同的5个选项.
I have 3 select statements that each share the same 5 options.
我如何确保当一个选项中的一个选项被选中时,它不会出现在另一个选项中?
How can i make sure that when an option is picked in one of the selects, it won't appear in any of the other?
<select>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
推荐答案
您可以使用HTML5 hidden
属性.如果您需要对非HTML5的支持,请改为使用disabled
属性.请注意,jQuery .hide()
不适用于所有浏览器.
You could use the HTML5 hidden
attribute. If you need support for non-HTML5, then go for the disabled
attribute instead. Note that jQuery .hide()
will not work in all browsers.
$(function () {
$('select').change(function() {
var used = new Set;
$('select').each(function () {
var reset = false;
$('option', this).each(function () {
var hide = used.has($(this).text());
if (hide && $(this).is(':selected')) reset = true;
$(this).prop('hidden', hide);
});
if (reset) $('option:not([hidden]):first', this).prop('selected', true);
used.add($('option:selected', this).text());
});
}).trigger('change'); // run at load
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
此解决方案将在第二个下拉菜单中减少一个选项,而在第三个下拉菜单中减少两个选项.在第一个下拉菜单中选择一个使用的选项将更改另一个下拉菜单.
This solution will make one less option available in the second drop-down, and two less in the third drop-down. Selecting a used option in the first drop-down will change the other drop-down selection.
另一种选择是只使用一个select
,并允许用户进行多项选择,并使用代码来防止选择超过3个项目:
The alternative is to just use one select
, and allow the user to make multiple selections, and use code to prevent selection of more than 3 items:
$('select').change(function() {
if ($(':selected', this).length > 3) {
$(':selected', this).slice(3).prop('selected', false);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple size=5>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
这篇关于唯一选择选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!