Home >Web Front-end >JS Tutorial >How Can I Check if a Checkbox is Selected Using jQuery?

How Can I Check if a Checkbox is Selected Using jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 18:18:11652browse

How Can I Check if a Checkbox is Selected Using jQuery?

Check if a Checkbox is Selected Using jQuery

Situation:

In jQuery, you need to determine if a checkbox is checked to perform specific actions, but the default attr('checked') method returns false when unchecked.

Solution:

1. Using DOM Element Properties:

  • Access the DOM element's checked property directly:
if(document.getElementById('isAgeSelected').checked) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

2. Toggling Visibility with toggle():

  • Use the toggle() method to show or hide an element based on the checkbox's checked state:
$('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
});

Note:

  • this.checked returns true if the checkbox is checked and false if it's unchecked.
  • toggle() shows the element if it's hidden and hides it if it's shown.

The above is the detailed content of How Can I Check if a Checkbox is Selected Using 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