如何检查jQuery中是否已选中复选框?

JavaScript

古一梅

2020-03-09

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

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

但是以下代码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属性?

第144篇《如何检查jQuery中是否已选中复选框?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
TomL 2020.03.09

Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked), this problem could be solved just by css. With this approach, your form works for users who have disabled JavaScript.

Assuming that you have the following HTML:

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

You can use the following CSS to achieve the desired functionality:

 #show_textbox:not(:checked) + input[type=text] {display:none;}

For other scenarios, you may think of appropriate CSS selectors.

Here is a Fiddle to demonstrate this approach.

斯丁ProJinJin 2020.03.09

1)如果您的HTML标记是:

<input type="checkbox"  />

attr used:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

If prop is used:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2) If your HTML markup is:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

attr used:

$(element).attr("checked") // Will return checked whether it is checked="true"

Prop used:

$(element).prop("checked") // Will return true whether checked="checked"
樱小小Tom 2020.03.09

我的方法是:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}
JimProL 2020.03.09

这为我工作:

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

isAgeSelected控件的ID 在哪里

另外,@ karim79的答案也很好。我不确定测试时错过了什么。

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

樱Harry 2020.03.09

从jQuery 1.6开始,的行为jQuery.attr()已更改,鼓励用户不要使用它来检索元素的选中状态。相反,您应该使用jQuery.prop()

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

其他两种可能性是:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")
猪猪GO 2020.03.09

我正在使用此,这绝对正常:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");

注意:如果选中此复选框,它将返回true,否则未定义,因此最好检查“ TRUE”值。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android