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
Release: 2024-12-17 18:18:11
Original
647 people have browsed it

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

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);
});
Copy after login

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!

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