How to Select Checked Checkboxes in jQuery

Selecting checked checkboxes using jQuery is a common requirement in web development for form processing, bulk actions, and dynamic filtering. This article explains the most reliable jQuery selectors to target checked checkbox inputs, demonstrates how to retrieve their values, and shows practical examples for counting and iterating through selected elements.


The Standard Selector

The most efficient and standard way to target checked checkboxes is using the standard CSS pseudo-class :checked combined with the attribute selector:

$('input[type="checkbox"]:checked')

While jQuery also supports the custom pseudo-selector $('input:checkbox:checked'), using input[type="checkbox"]:checked is recommended because it can leverage the browser's native querySelectorAll() method, making it significantly faster.


Getting the Values of Checked Checkboxes

To extract the values of all currently selected checkboxes into a JavaScript array, use jQuery's .map() and .get() methods:

const checkedValues = $('input[type="checkbox"]:checked').map(function() {
    return $(this).val();
}).get();

console.log(checkedValues); // Output: Array of values, e.g., ["apple", "banana"]

Iterating Through Each Checked Checkbox

If you need to perform an action on every checked checkbox individually (such as logging an ID or modifying attributes), use the .each() method:

$('input[type="checkbox"]:checked').each(function() {
    console.log("Checked ID: " + $(this).attr('id'));
    console.log("Value: " + $(this).val());
});

Counting Checked Checkboxes

To determine how many checkboxes are currently checked, access the .length property:

const totalChecked = $('input[type="checkbox"]:checked').length;
console.log("Total checked: " + totalChecked);

Targeting Checkboxes Within a Specific Container

To avoid selecting checkboxes from other parts of the page, scope the selector to a specific form or container element:

// Within a form with ID 'myForm'
$('#myForm input[type="checkbox"]:checked')

// Within a specific class container
$('.filter-group').find('input[type="checkbox"]:checked')