如何检查是否在jQuery中检查了一个复选框? [英] How to check whether a checkbox is checked in jQuery?

查看:153
本文介绍了如何检查是否在jQuery中检查了一个复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个复选框的选中的属性,并使用jQuery执行基于checked属性的操作。



例如,如果选中年龄复选框,则需要显示一个文本框以输入年龄,否则隐藏文本框。



但是以下代码返回 false 默认情况下:

  if($('#isAgeSelected')。 attr('checked')){
$(#txtAge)。show();
} else {
$(#txtAge)。hide();
}

如何成功查询检查 property?

解决方案


如何成功查询已检查的属性? >

复选框DOM元素的检查属性将为您提供 /> code code code
$ b

鉴于您现有的代码,您可以这样做:



pre> if(document.getElementById('isAgeSelected')。checked){
$(#txtAge)。
} else {
$(#txtAge)。hide();
}

然而,有一个更漂亮的方法来做到这一点,使用 toggle



点击(function(){$(#txtAge)。(这个。选择);});

 < 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆