如何检查jQuery中是否已选中复选框? [英] How do I check whether a checkbox is checked in jQuery?

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

问题描述

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

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.

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

But the following code returns false by default:

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>

我如何成功是否确实查询了选中的属性?

How do I successfully query the checked property?

推荐答案


如何成功查询选中的属性?

How do I successfully query the checked property?

选中的属性复选框DOM元素将为您提供该元素的已检查状态。

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天全站免登陆