我需要检查一个复选框的 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
属性?
最佳答案
How do I successfully query the checked property?
复选框 DOM 元素的 checked
属性将为您提供元素的 checked
状态。
鉴于您现有的代码,您可以这样做:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
但是,有一个更漂亮的方法可以做到这一点,使用 toggle
:
$('#isAgeSelected').click(function() {
$("#txtAge").toggle(this.checked);
});
<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 something</div>
https://stackoverflow.com/questions/901712/