Explain Codes LogoExplain Codes Logo

Getting all selected checkboxes in an array

javascript
dom-querying
event-delegation
vanilla-javascript
Anton ShumikhinbyAnton Shumikhin·Nov 5, 2024
TLDR

Swiftly grab all checked checkboxes using querySelectorAll and list all the values into an array:

const selected = [...document.querySelectorAll('input[type=checkbox]:checked')].map( checkbox => checkbox.value);

Common Approaches and Scenario-Based Solutions

To help grasp how we can expand on the basic answer, we will explore more context-based solutions and alternative methods for different possible scenarios.

Leveling up with jQuery

If jQuery is in your toolbox, you can utilize its simplified syntax:

let selected = $('input[type=checkbox]:checked').map(function() { return this.value; }).get(); // jQuery really saves the day! No pain, more gain!

This single line of code elegantly takes care of DOM selection, iteration, and array conversion.

Forms and checkboxes

When it comes to forms, serializing the array becomes beneficial, especially for server submissions:

const formData = $('form').serializeArray(); // Who knew forms could be this easy? Serialization for the win!

Targeting specific checkboxes

At times, you perhaps need to fetch checkboxes of a specific name:

const namedCheckboxes = $(`input[type=checkbox][name="myCheckbox"]:checked`).map((_, checkbox) => checkbox.value).get(); // Like an elite sniper, this targets the checkboxes with the name "myCheckbox"

Using more particular name selectors, you can make your queries more precise and robust!

Advanced Usages and Additional Scenarios

Peeling off further layers, let's discuss important aspects and scenarios that could enrich your programming dexterity.

Infinite loading... Beating it with jQuery

Remember the golden rule of jQuery - Beat the loading race:

$(document).ready(function() { // Now that DOM's ready, let the Checkbox party begin! });

This ensures that the party doesn't start before everyone's arrived! (AKA, all DOM elements are ready for scripting.)

Dancing with dynamically added checkboxes

In cases where you have dynamic DOM updates (common in SPA or Ajax-powered sites), consider event delegation:

$(document).on('change', 'input[type=checkbox]', function() { // Like a smooth sea navigator, we sail through dynamic DOM changes! });

Rocking it vanilla style

While jQuery is quite sweet, sometimes vanilla JavaScript tastes even better:

document.addEventListener('DOMContentLoaded', function() { // Just like a rockstar greeting fans, JavaScript waits for DOM's readiness! });

And just like that, you don't even need jQuery. Stick to specific selectors to be a DOM querying rockstar!