Bat*_*fan 5 html forms jquery select
我正在开展一个项目,我的表格中有多个"选择"输入,所有输入都有相同的选项.我想使用jquery来禁用/隐藏其余"select"输入中的选项(如果已经选中).
例如:
<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>
Run Code Online (Sandbox Code Playgroud)
用户在第一次选择时选择"Volvo".我想从第二个选择中删除它.
任何信息,将不胜感激.
这里有代码可以继续选择和禁用我们想要的所有时间.
首先是启用每个选项,然后查看选定的值,并禁用与所选值一致的选项.
这两个步骤至关重要,因为如果再次选择,将禁用之前的禁用值.
最新版本
更优雅的方式,我们使用map()(在stackoverflow中有关于此方法的一个很好的解释)和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");
});
Run Code Online (Sandbox Code Playgroud)
新版本
我编辑了我的答案,这是我的最终版本:
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");
}
Run Code Online (Sandbox Code Playgroud)
旧版
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");
}
Run Code Online (Sandbox Code Playgroud)