Dav*_*vid 41 html javascript select
我有<select>一些<option>s.每个都有一个独特的价值.我需要禁用<option>具有给定定义值(不是innerhtml)的a.
任何人都知道如何?
Sam*_*son 78
使用纯Javascript,您必须遍历每个选项,并单独检查它的值.
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
Run Code Online (Sandbox Code Playgroud)
不启用非目标元素:
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
Run Code Online (Sandbox Code Playgroud)
使用jQuery,您可以使用一行执行此操作:
$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
Run Code Online (Sandbox Code Playgroud)
不启用非目标元素:
$("option[value='stackoverflow']").attr("disabled", "disabled");
Run Code Online (Sandbox Code Playgroud)
请注意,这不是不区分大小写的."StackOverflow"不等于"stackoverflow".要获得不区分大小写的匹配,您必须遍历每个,将值转换为小写,然后检查:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
Run Code Online (Sandbox Code Playgroud)
不启用非目标元素:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});
Run Code Online (Sandbox Code Playgroud)
小智 5
为该选项设置一个 id,然后使用按 id 获取元素并在选择 x 值时禁用它。
例子
<body>
<select class="pull-right text-muted small"
name="driveCapacity" id=driveCapacity onchange="checkRPM()">
<option value="4000.0" id="4000">4TB</option>
<option value="900.0" id="900">900GB</option>
<option value="300.0" id ="300">300GB</option>
</select>
</body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){
document.getElementById("driveCapacity").value = "4000.0";
document.getElementById("4000").disabled = false;
}else{
document.getElementById("4000").disabled = true;
}
</script>
Run Code Online (Sandbox Code Playgroud)