当我的页面加载时,我希望禁用所有未选中的框:
<form action="demo_form.asp" method="get">
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
<input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)
我尝试使用此代码,但它无法正常工作:
$(document).ready(function(){
if($(".test").is(':checked'))
$(".test").attr("disabled", false);
else
$(".test").attr("disabled", true);
});
Run Code Online (Sandbox Code Playgroud)
您可以使用:not(:checked)筛选未选中的复选框
$(document).ready(function() {
$(":checkbox:not(:checked)").prop('disabled', true)
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="demo_form.asp" method="get">
<input type="checkbox" name="vehicle" value="Bike">I have a bike
<br>
<input type="checkbox" name="vehicle" value="Car" checked>I have a car
<br>
<input type="submit" value="Submit">
</form>Run Code Online (Sandbox Code Playgroud)
您也可以使用prop()回调
$(document).ready(function() {
$(":checkbox").prop('disabled', function() {
return !this.checked;
})
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="demo_form.asp" method="get">
<input type="checkbox" name="vehicle" value="Bike">I have a bike
<br>
<input type="checkbox" name="vehicle" value="Car" checked>I have a car
<br>
<input type="submit" value="Submit">
</form>Run Code Online (Sandbox Code Playgroud)
注意:在你的代码中我看不到test类,所以我:checkbox用来引用所有复选框.