show a list of checkboxes that have been selected using JavaScript

I have a group of Checkbox options for 7 Days all with the same name of "sessionDays." I have used the following code to count the number of checked checkboxes:

var totalDays = document.querySelectorAll('.sessionDays input[type="checkbox"]:checked').length;

Now, I am trying to display a list of selected checkboxes in HTML using Javascript without using jQuery. I have searched through various resources but have not found a solution.

Below is my HTML:

<div class="days sessionDays">
                    <label>Select Session Days</label>
                    <p class="text-muted">Choose the specific days you wish to attend training.</p>
                    <div class="form-check">
                      <input class="form-check-input weekend" type="checkbox" value="1" id="sessionSunday" name="sessionDays" onFocus="startCalc();" onBlur="stopCalc();" onclick="resetMorning();">
                      <label class="form-check-label" for="sessionSunday">
                        Sunday
                      </label>
                    </div>
                    <div class="form-check">
                      <input class="form-check-input weekday" type="checkbox" value="1" id="sessionMonday" name="sessionDays" onFocus="startCalc();" onBlur="stopCalc();" onclick="resetEvening();">
                      <label class="form-check-label" for="sessionMonday">
                        Monday
                      </label>
                    </div>
                    <div class="form-check">
                      <input class="form-check-input weekday" type="checkbox" value="1" id="sessionTuesday" name="sessionDays" onFocus="startCalc();" onBlur="stopCalc();" onclick="resetEvening();">
                      <label class="form-check-label" for="sessionTuesday">
                        Tuesday
                      </label>
                    </div>
                    <div class="form-check">
                      <input class="form-check-input weekday" type="checkbox" value="1" id="sessionWednesday" name="sessionDays" onFocus="startCalc();" onBlur="stopCalc();" onclick="resetEvening();">
                      <label class="form-check-label" for="sessionWednesday">
                        Wednesday
                      </label>
                    </div>
                    <div class="form-check">
                      <input class="form-check-input weekday" type="checkbox" value="1" id="sessionThursday" name="sessionDays" onFocus="startCalc();" onBlur="stopCalc();" onclick="resetEvening();">
                      <label class="form-check-label" for="sessionThursday">
                        Thursday
                      </label>
                    </div>
                    <div class="form-check">
                      <input class="form-check-input weekday" type="checkbox" value="1" id="sessionFriday" name="sessionDays" onFocus="startCalc();" onBlur="stopCalc();" onclick="resetEvening();">
                      <label class="form-check-label" for="sessionFriday">
                        Friday
                      </label>
                    </div>
                    <div class="form-check">
                      <input class="form-check-input weekend" type="checkbox" value="1" id="sessionSaturday" name="sessionDays" onFocus="startCalc();" onBlur="stopCalc();" onclick="resetMorning();">
                      <label class="form-check-label" for="sessionSaturday">
                        Saturday
                      </label>
                    </div>
                  </div>

Check out the JSFiddle link for reference: http://jsfiddle.net/humanware/rjfjp2mL/

Answer №1

You are on the right track, just a little more to go. Once you execute the querySelectorAll function, it will provide you with an array containing the checked controls. Try out the following code snippet:

<html>
<head>
    <title>Random</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>

    <div class="days sessionDays">
        <label>Select Session Days</label>
        <p class="text-muted">Choose the specific days you wish to attend the training session.</p>
        <div class="form-check">
            <input class="form-check-input weekend" type="checkbox" value="1" id="sessionSunday" name="sessionDays" onclick="whatsChecked();">
            <label class="form-check-label" for="sessionSunday">
                Sunday
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input weekday" type="checkbox" value="1" id="sessionMonday" name="sessionDays" onclick="whatsChecked();">
            <label class="form-check-label" for="sessionMonday">
                Monday
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input weekday" type="checkbox" value="1" id="sessionTuesday" name="sessionDays" onclick="whatsChecked();">
            <label class="form-check-label" for="sessionTuesday">
                Tuesday
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input weekday" type="checkbox" value="1" id="sessionWednesday" name="sessionDays" onclick="whatsChecked();">
            <label class="form-check-label" for="sessionWednesday">
                Wednesday
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input weekday" type="checkbox" value="1" id="sessionThursday" name="sessionDays" onclick="whatsChecked();">
            <label class="form-check-label" for="sessionThursday">
                Thursday
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input weekday" type="checkbox" value="1" id="sessionFriday" name="sessionDays" onclick="whatsChecked();">
            <label class="form-check-label" for="sessionFriday">
                Friday
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input weekend" type="checkbox" value="1" id="sessionSaturday" name="sessionDays" onclick="whatsChecked();">
            <label class="form-check-label" for="sessionSaturday">
                Saturday
            </label>
        </div>
    </div>
    <script type="text/javascript">
        function whatsChecked() {
            var foo = [];
            var checkedInputs = document.querySelectorAll('.sessionDays input[type="checkbox"]:checked');
            for (var i = 0; i < checkedInputs.length; i++) {
                foo[i] = checkedInputs[i].id;
            }
            for (var i = 0; i < checkedInputs.length; i++) {
                console.log(checkedInputs[i].id);
            }
        }

    </script>
</body>
</html>

Answer №2

const checkedDays = document.querySelectorAll('.sessionDays input[type="checkbox"]:checked'); const totalCheckedDays = checkedDays.length;

Array.from(checkedDays).forEach((item, index) => {
// code to show each checked checkbox (item)
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you use jQuery to transform a H3 tag into a clickable link?

To transform the h3 tag into a clickable link with jQuery and set the href attribute, while preserving the H3 styling and adding an anchor tag, you can use the following code as an example: Click Here ...

Unusual express middleware usage in NodeJS

app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.get('/2',function(req,res){ console.log('/2'); res.end() ...

Exploring JSON data structures using autocomplete functionalities

Here's the code I'm working with: <s:hidden id="s" value="%{Users}"/> The variable Users contains an array list of User objects. This code is written in Javascript. I want to access Users as JSON for auto-complete functionality: var valu ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

Eliminating unique phrases from text fields or content sections with the help of jQuery or JavaScript

I'm currently working on a PHP website and have been tasked with the responsibility of removing certain special strings such as phone numbers, email addresses, Facebook addresses, etc. from a textarea that users input data into. My goal is to be able ...

Adjust the Angular menu-bar directly from the content-script of a Chrome Extension

The project I've been working on involves creating an extension specifically for Google Chrome to enhance my school's online learning platform. This website, which is not managed by the school itself, utilizes Angular for its front-end design. W ...

Tips for adding a string variable to a JQuery HTML element attribute

Hi there, I've been working on a JQuery code to append data to a div element and it's been successful so far. Here is the code: $('#conversation').append('<div id="receiver"><p><b>' + username + ':< ...

How to dynamically update form select options using Zend Framework 2 (2.3) and AJAX

I'm facing an issue with concatenating 3 dynamic selects - state, country, city - using an ajax request. It seems more complex without zf2! The function works fine when $idState is manually set within stateCountryCityAction (e.g. $idState = 1;), but d ...

The numbering in the list does not align vertically with the corresponding content

I am attempting to create an ordered list with collapsible sections inside the li elements. The goal is to display basic information about a specific context, and when clicking on a link, additional details are shown. While the code is functional, I am fac ...

Vue's reactivity in Vue 3 is exhibiting strange behavior with boolean data

Currently, I am attempting to modify a boolean variable. Upon the initial page load, everything works as expected. However, upon reloading the page, the variable gets updated locally within the method but not in the global data section. As a result, an err ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...

Enhance Bootstrap 4's Carousel with a centered caption or content that is both vertically and horizontally aligned

Looking to enhance the standard captions of Bootstrap 4's carousel element, I aim to elegantly overlay a static caption in a responsive manner across a full-screen carousel. While there are solutions available online that involve absolutely positionin ...

The Blueimp File Uploader seems to be sending numerous submissions at once

I've been tasked with fixing an issue on our site that I didn't originally build. The previous developer who worked on this project is now occupied with another task, leaving me to figure out what's going wrong. We are utilizing the basic bl ...

Error occurs when attempting to read the 'map' properties of null because the JSON array is double nested

Within my code, I am attempting to access the URLs of two thumbnails in the JSON data below. Currently, I can only retrieve the information from the first array: <>{post.attributes.description}</> However, I am encountering difficulty retrievi ...

Issue with Angular ng-model not functioning as expected within ng-repeat block

Encountering an issue when trying to bind Json data into ng-model within ng-repeat. html : <div ng-controller="Ctrl"> <div> <table> <th> <td>add</td> <td>ed ...

What is causing ui-route to fail in resolving state1 when transitioning from state2?

I have a program that consists of two views (lefthandmenu and content), with modules. When the user selects a module from a combo-list, $state.go() is called with the selected module name, and the views should update accordingly. See code samples below. I ...

What is the best way to send JavaScript data to PHP?

Is it possible to post a variable to a PHP script without refreshing the page? If so, how can this be achieved? Here is an example using jQuery: $.ajax({ url: "myphpfile.php", type: "post", data: json/array/whatever, success: function(){ ...

Ensuring proper alignment within anchor links and buttons

button, a { height: 30px; display: inline-block; border: 1px solid black; vertical-align: middle; } button > div, a > div { width: 30px; height: 10px; background-color: red; } <button> <div class="buttonDiv"></div> ...

Encountering a npm error E404 when trying to install unicons package for React development

I recently started working on a weather app project using create-react-app and encountered an issue while trying to install unicons for the project. Despite attempting a few solutions, I was unable to resolve the problem. Here is the command I used for th ...

Exploring the growth of CSS offsetting alongside with AngularJS

I am working on an Angular app where I need to increase the left offset of a div by 90px every time the slideThis() function is called. In jQuery, I would typically achieve this using left: '+=90', but I'm struggling to find a similar method ...