## jQuery :checked Selector
The `:checked` selector is a built-in jQuery filter used to target and select all form elements that are currently checked or selected. This primarily applies to checkboxes (`
`) and radio buttons (`
`).
---
## Definition and Usage
The `:checked` selector matches all elements that are toggled to an "active" or "selected" state. It is highly useful for form validation, dynamic UI updates, and retrieving user-selected values in real-time.
### Key Characteristics:
* **Target Elements:** It specifically targets `
` elements of type `checkbox` and `radio`.
* **Dropdowns Note:** While HTML `
` elements in a `` dropdown can also be "selected", jQuery provides a dedicated `:selected` selector for them. However, in some browser environments, `:checked` may also retrieve selected `` elements. To ensure robust, cross-browser compatibility, always use `:checked` for checkboxes/radio buttons and `:selected` for dropdown menus.
---
## Syntax
```javascript
$(":checked")
```
To make your selectors more precise and performant, it is highly recommended to prefix the selector with an element type or a container ID:
```javascript
// Selects only checked checkboxes
$("input[type='checkbox']:checked")
// Selects only checked radio buttons
$("input[type='radio']:checked")
// Selects checked elements within a specific form
$("#myForm :checked")
```
---
## Code Examples
### Example 1: Basic Usage (Count Checked Items)
The following example counts the number of checked checkboxes and displays the count in real-time when a user clicks them.
```html
jQuery :checked Selector Demo
Select your favorite programming languages:
You have selected 0 item(s).
```
### Example 2: Get Values of Selected Radio Buttons
This example demonstrates how to retrieve the value of the currently selected radio button.
```javascript
$(document).ready(function(){
$("input[type='radio']").change(function(){
// Get the value of the selected radio button in the 'gender' group
var selectedGender = $("input[name='gender']:checked").val();
console.log("Selected Gender: " + selectedGender);
});
});
```
---
## Technical Considerations & Best Practices
1. **Performance Optimization:**
Using the universal selector `$(":checked")` forces jQuery to traverse the entire DOM. For better performance, especially in large documents, prefix the selector with the element type (e.g., `$("input:checked")`).
2. **Difference between `:checked` and `.prop('checked')`:**
* Use the **`:checked` selector** when you want to *find* or *filter* elements in the DOM.
* Use the **`.prop('checked')` method** when you want to *get* or *set* the checked state of a specific element programmatically.
```javascript
// Check if a specific element is checked
if ($("#myCheckbox").prop("checked")) {
// Do something
}
// Programmatically check a checkbox
$("#myCheckbox").prop("checked", true);
```