在jQuery中如何检查一个复选框是否被选中?

发布时间 2023-10-12 20:25:49作者: 小满独家

内容来自 DOC https://q.houxu6.top/?s=在jQuery中如何检查一个复选框是否被选中?

我需要检查复选框的checked属性,并根据该属性使用jQuery执行操作。

例如,如果age复选框被选中,那么我需要显示一个文本框以输入age,否则隐藏该文本框。

但是以下代码默认返回false

if ($('#isAgeSelected').attr('checked')) {
  $("#txtAge").show();
} else {
  $("#txtAge").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">
  Age is selected
</div>

我该如何成功查询checked属性?


这对我来说有效:

$get("isAgeSelected").checked == true

其中isAgeSelected是控件的id。

此外,@karim79的回答也可以正常工作。我不确定我当时测试时错过了什么。

注意,此答案使用的是Microsoft Ajax,而不是jQuery