如何用jQuery检查一个复选框
有两种方法可以通过改变输入类型的checked属性来动态地检查当前选择的复选框。
方法1:使用prop方法:可以通过使用prop方法访问输入并设置其属性。这个方法操作’checked’属性,并根据我们是否要检查或取消检查,将其设置为真或假。
语法:
$("element").prop("checked", true)
示例:
<!DOCTYPE html>
<head>
<title>
How to check a checkbox with jQuery?
</title>
<script src=
"https://code.jquery.com/jquery-2.2.4.min.js">
</script>
</head>
<body>
<center>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
jQuery Check/Uncheck Checkbox
</b>
<p>
<input type="checkbox" name="option" id="front">
Front-End
<input type="checkbox" name="option" id="back">
Back-End
</p>
<p>
<button type="button" class="check-front">
Subscribe Front-End
</button>
<button type="button" class="check-back">
Subscribe Back-End
</button>
<button type="button" class="reset">
Reset
</button>
</p>
<script type="text/javascript">
(document).ready(function() {
(".check-front").click(function() {
("#front").prop("checked", true);
});
(".check-back").click(function() {
("#back").prop("checked", true);
});
(".reset").click(function() {
("#front").prop("checked", false);
("#back").prop("checked", false);
});
});
</script>
</center>
</body>
</html>
输出:
- 在点击任何按钮之前。
- 点击按钮。
- 点击 “重置 “按钮。
方法2:使用attr方法 : 它与上述方法类似,更适合于旧的jQuery版本。通过使用attr方法,输入可以被访问,其属性可以被设置。我们必须操作’checked’属性,并根据我们是否要检查或取消检查,将其设置为true或false。
注意:在设置属性为 “true “时,有必要添加一个点击方法,以确保该选项在选项组中得到更新。
语法:
$("element").attr("checked", true)
示例:
<!DOCTYPE html>
<head>
<title>
How to check a checkbox with jQuery?
</title>
<script src=
"https://code.jquery.com/jquery-2.2.4.min.js">
</script>
</head>
<body>
<center>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
jQuery Check/Uncheck Checkbox
</b>
<p>
<input type="checkbox" name="option" id="Front">
Front-End
<input type="checkbox" name="option" id="Back">
Back-End
</p>
<p>
<button type="button" class="check-Front">
Subscribe Front-End
</button>
<button type="button" class="check-Back">
Subscribe Back-End
</button>
<button type="button" class="reset">
Reset
</button>
</p>
<script type="text/javascript">
(document).ready(function() {
(".check-Front").click(function() {
("#Front").attr("checked", true);
});
(".check-Back").click(function() {
("#Back").attr("checked", true);
});
(".reset").click(function() {
("#Front").attr("checked", false);
("#Back").attr("checked", false);
});
});
</script>
</center>
</body>
</html>
输出:
- 在点击任何按钮之前。
- 点击按钮。
- 点击 “重置 “按钮。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。