如何使用jQuery防止多个下拉列表中的重复值 [英] How to prevent duplicate values in multiple dropdowns using jQuery

查看:11
本文介绍了如何使用jQuery防止多个下拉列表中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 5 个下拉菜单供用户选择他们的偏好.所有下拉菜单都有相同的选择.如果用户为下拉列表 1 选择了一个值,则该选项不应可用于其他下拉列表.如此下去,最后一个下拉菜单应该有 4 个不可选择的选项.

I have 5 dropdowns menu for users to select their preferences. All the dropdowns have the same choices. If the user has chosen a value for dropdown 1, that option should not be available for the other dropdowns. And it goes on so, for the last dropdown, there should be 4 unselectable options.

它类似于在这个链接上所做的.但现在我们有超过 2 个下拉菜单.

It's similar to what is done on this link. But now we have more than 2 dropdowns.

(For illustration, I show three dropdowns only)    

<select id="_go">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<select id="_gogo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<select id="_gogogo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

以下代码适用于两个下拉列表,但不能超过 2 个.

The below codes works fine for two dropdowns, but not for more than 2.

var $select = $("select[id$='go']");
$select.change(function() {
    $select
      .not(this)
      .find('option')
      .prop('disabled', '')
      .filter('[value='+this.value+']')
      .prop('disabled','disabled');
});
$select.eq(0).trigger('change');

我要注意的是,用户可能不小心点击了其中一个下拉列表的错误选项,因此如果用户再次选择,则应再次启用原始值.

I thing to notice is that a user may accidentally clicked for a wrong option for one of the dropdowns, so if the user select again, the original value should be enabled again.

请提出一个方法.提前致谢.

Please suggest a way. Thanks in advance.

推荐答案

不要立即更改选项的状态,首先您需要获取选择字段中的当前值,以便您可以在其他选择字段中禁用它们

演示

Instead of changing the status of the option right away, first you need to get current values in the select fields, so that you can disable them in other select fields

demo

 $(".go").change(function(){
    var selVal=[];
    $(".go").each(function(){
        selVal.push(this.value);
    });

    $(this).siblings(".go").find("option").removeAttr("disabled").filter(function(){
       var a=$(this).parent("select").val();
       return (($.inArray(this.value, selVal) > -1) && (this.value!=a))
    }).attr("disabled","disabled");
});

$(".go").eq(0).trigger('change');


上面的代码可以与任意数量的选择框一起使用:)


the above code can be used with any number of select boxes :)

这篇关于如何使用jQuery防止多个下拉列表中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆