我正在从事一个项目,其中我有一个表单,该表单将具有多个“选择”输入,所有输入都具有相同的选项集。我想使用 jquery 来禁用/隐藏其余“选择”输入中的选项,如果它已经被选中的话。
例如:
<select id="1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
</select>
<select id="2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
</select>
用户在第一次选择时选择“沃尔沃”。我希望将它从第二个选择中删除。
如有任何信息,我们将不胜感激。
最佳答案
这里有我们想要的所有时间继续选择和禁用的代码。
首先是启用每个选项,然后查看所选值,并禁用与所选值一致的选项。
这两个步骤很关键,因为如果您再次选择,之前禁用的值将继续禁用。
最新版本
更优雅的方式,我们使用 map() ( in stackoverflow there is a good explanation about this method ) 和 filter() jquery 函数来完成这项工作。行数更少,我认为性能相同或更好。
http://www.jsfiddle.net/dactivo/keDDr/
$("select").change(function()
{
$("select option").attr("disabled",""); //enable everything
//collect the values from selected;
var arr = $.map
(
$("select option:selected"), function(n)
{
return n.value;
}
);
//disable elements
$("select option").filter(function()
{
return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
}).attr("disabled","disabled");
});
新版本
我已经编辑了我的答案,这是我的最终版本:
http://www.jsfiddle.net/dactivo/kNbWc/
$("select").change(function()
{
$("select option").attr("disabled",""); //enable everything
DisableOptions(); //disable selected values
});
function DisableOptions()
{
var arr=[];
$("select option:selected").each(function()
{
arr.push($(this).val());
});
$("select option").filter(function()
{
return $.inArray($(this).val(),arr)>-1;
}).attr("disabled","disabled");
}
旧版本
http://www.jsfiddle.net/AyxL3/
$("select").change(function()
{
$("select option").attr("disabled",""); //enable everything
DisableOptions(); //disable selected values
});
function DisableOptions()
{
$("select option").filter(function()
{
var bSuccess=false; //will be our flag to know it coincides with selected value
var selectedEl=$(this);
$("select option:selected").each(function()
{
if($(this).val()==selectedEl.val())
{
bSuccess=true; //it coincides we will return true;
return false; // this serves to break the each loop
}
});
return bSuccess;
}).attr("disabled","disabled");
}
关于jquery - 防止多次选择相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4001805/