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
Susan SarandonOriginal
2024-12-20 18:59:17796browse

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();
}

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();
}

Option 2:

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

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

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!

Statement:
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