Home > Web Front-end > JS Tutorial > How to Accurately Check a Checkbox's Checked Status with jQuery?

How to Accurately Check a Checkbox's Checked Status with jQuery?

Susan Sarandon
Release: 2024-12-20 18:59:17
Original
739 people have browsed it

How to Accurately Check a Checkbox's Checked Status with jQuery?

Checking the Checked Property of a Checkbox with jQuery

Problem:

You need to determine the checked status of a checkbox using jQuery and take an action based on the result.

jQuery Code:

The following jQuery code attempts to check the checked property of the "isAgeSelected" checkbox but returns false by default:

if ($('#isAgeSelected').attr('checked')) {
  $("#txtAge").show();
} else {
  $("#txtAge").hide();
}
Copy after login

Correct Solution:

To query the checked property successfully, you can use the following code:

Option 1:

Access the DOM element directly using JavaScript:

if(document.getElementById('isAgeSelected').checked) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}
Copy after login

Option 2:

Use jQuery's "toggle" function for a cleaner approach:

$('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
});
Copy after login

This code handles the click event on the "isAgeSelected" checkbox and toggles the visibility of the "txtAge" element based on the checked state.

The above is the detailed content of How to Accurately Check a Checkbox's Checked Status with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template