Collect All the Selected Checkboxes Into an Array After Clicking a Button in Javascript

If you have multiple checkboxes and you want to collect all the selected checkboxes into an array after clicking a button, you can achieve this using JavaScript. Here’s an example of how you can do it:


<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple Checkboxes Example</title>

    <h2>Multiple Checkboxes</h2>
    <input type="checkbox" id="checkbox1"> Checkbox 1
    <input type="checkbox" id="checkbox2"> Checkbox 2
    <input type="checkbox" id="checkbox3"> Checkbox 3

    <button id="collectBtn">Collect Selected Checkboxes</button>

    <script src="script.js"></script>


JavaScript (script.js):

document.getElementById('collectBtn').addEventListener('click', function() {
    var checkboxes = document.querySelectorAll('input[type=checkbox]:checked');
    var selectedCheckboxesArray = [];

    checkboxes.forEach(function(checkbox) {

    console.log('Selected Checkboxes: ', selectedCheckboxesArray);

In this example, we have three checkboxes with unique IDs (checkbox1, checkbox2, and checkbox3). When you click the “Collect Selected Checkboxes” button, the JavaScript code will find all the checkboxes that are checked, collect their IDs, and store them in the selectedCheckboxesArray. The IDs of the selected checkboxes are then logged to the console.

This code assumes that each checkbox has a unique ID. You can modify the logic inside the event listener according to your specific use case if you need to collect different information about the selected checkboxes.