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