如您所见,我有一个带有 select2(多个)选择功能的选择框,其中有一些选项,例如
<option value="All"> All </option>
<option value="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb9f8e989fab8e868a8287c5888486" rel="noreferrer noopener nofollow">[email protected]</a>"> User 1</option>
<option value="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd89988e89cfbd98909c9491d39e9290" rel="noreferrer noopener nofollow">[email protected]</a>"> User 2 </option>
<option value="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="de8abbadaaed9eacb3bfb7b2f0bdb1b3" rel="noreferrer noopener nofollow">[email protected]</a>"> User 3 </option>
是否有可能,如果我从选择框中选择选项All
,那么选择框不允许我从给定选项中选择其他选项,除非我将其删除。
我想限制用户选择“全部”或从选项中选择多个用户。
我准备使用 jQuery 或 javascript 来实现这一点。
最佳答案
<强> Working fiddle 。
当选项All
出现时,您可以将select的值设置为All:
$("#my-select").select2();
$("#my-select").on('change', function(){
var selected = $(this).val();
if(selected != null)
{
if(selected.indexOf('All')>=0){
$(this).val('All').select2();
}
}
})
希望这有帮助。
$("#my-select").select2();
$("#my-select").on('change', function(){
var selected = $(this).val();
if(selected != null)
{
if(selected.indexOf('All')>=0){
$(this).val('All').select2();
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css" rel="stylesheet"/>
<select multiple id="my-select" style="width:300px">
<option value="All"> All </option>
<option value="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="374352444377525a565e5b1954585a" rel="noreferrer noopener nofollow">[email protected]</a>"> User 1</option>
<option value="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f286978186c0b2979f939b9edc919d9f" rel="noreferrer noopener nofollow">[email protected]</a>"> User 2 </option>
<option value="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c397a6b0b7f083b1aea2aaafeda0acae" rel="noreferrer noopener nofollow">[email protected]</a>"> User 3 </option>
</select>
关于javascript - 如果使用 select2 选择了特定值,则不允许选择其他选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40503680/