Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

javascript - 如何检查jQuery中是否已选中复选框?(How to check whether a checkbox is checked in jQuery?)

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery. (我需要检查复选框的checked属性,并使用jQuery根据checked属性执行操作。)

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: (但是以下代码默认情况下返回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> 

How do I successfully query the checked property? (如何成功查询checked属性?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. (复选框DOM元素的checked属性将为您提供该元素的checked状态。)

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 : (但是,使用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> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...