如何检查在jQuery中是否选中了复选框? [英] How do I check if a checkbox is checked in jQuery?
问题描述
我需要检查复选框的检查
属性,并使用jQuery基于选中的属性执行操作。
例如,如果选中了年龄复选框,则我需要显示一个文本框以输入age,否则隐藏文本框。
但是下面的代码返回 false
默认情况下:
if($('#isAgeSelected')。 attr('checked')){
$(#txtAge)。show();
} else {
$(#txtAge)。hide();
}
如何成功查询 c $ c> property
如何成功查询checked属性? >
复选框DOM元素的检查
属性将为您提供
$ b $ b
if(document.getElementById('isAgeSelected')。checked){
$(#txtAge)。
} else {
$(#txtAge)。hide();但是,有一个更漂亮的方法来做到这一点,使用 http://api.jquery.com/toggle/ =nofollow noreferrer> toggle
:
$('#isAgeSelected')click(function(){$(#txtAge)。toggle .checked);});
< script src = https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"> ;</script> ;<input type =checkboxid =isAgeSelected/> < div id =txtAgestyle =display:none>年龄是< / div>
I need to check the checked
property of a checkbox and perform an action based on the checked property using jQuery.
For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.
But the following code returns false
by default:
if($('#isAgeSelected').attr('checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
How do I successfully query the checked
property?
解决方案
How do I successfully query the checked property?
The checked
property of a checkbox DOM element will give you the checked
state of the element.
Given your existing code, you could therefore do this:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
However, there's a much prettier way to do this, using 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>
这篇关于如何检查在jQuery中是否选中了复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!