Is there a way to incorporate the sum of selected checkbox numbers into this jQuery or JavaScript code?

I am trying to figure out how to add and display the count of checked checkboxes with this set of codes.

Here's how the checkboxes function: There is a parent checkbox (Checkall) and multiple child checkboxes; when the parent checkbox is checked, it selects all child checkboxes and reveals a div. When each child checkbox (Single) is checked, the div is displayed as well. If the Parent/Child checkbox is unchecked, the div hides using jQuery hide and show methods.

The issue I am facing is adding a checkbox counter to the code. I need to display the count when the parent checkbox (Check all) is checked, as well as when individual child checkboxes (Single) are checked while still maintaining the functionality of showing and hiding the div.

Your assistance is greatly appreciated. Feel free to enhance or rewrite the code provided below:

$(document).ready(function() {
  $('#global').click(function() {
    $('.child').prop('checked', $(this).is(':checked'));

    if ($(this).is(':checked'))
      $('#mydiv').show();
    else
      $('#mydiv').hide();
  });

  $('.child').change(function() {
    var checkedLength = $('.child:checked').length;
    if (checkedLength > 0)
      $('#mydiv').show();
    else
      $('#mydiv').hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv" style="display:none;">RESTORE | DELETE</div>

<input type="checkbox" id="global">
<br>
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">

I appreciate your help :)

Answer №1

This code snippet shows how to track the number of checked child checkboxes:

$(document).ready(function() {
  $('#global').click(function() {
    $('.child').prop('checked', $(this).is(':checked'));

    if ($(this).is(':checked'))
      $('#mydiv').show();
    else
      $('#mydiv').hide();

    count();
  });

  $('.child').change(function() {
    var checkedLength = $('.child:checked').length;
    if (checkedLength > 0)
      $('#mydiv').show();
    else
      $('#mydiv').hide();
    count();
  });
});

var count = function() {
   var i = $('input.child:checked').length;
   $('#counter').html(i);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv" style="display:none;">RESTORE | DELETE
<span>Checked: </span>
<span id="counter"></span>
</div>

<input type="checkbox" id="global">
<br>
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">

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

I'm looking to implement a feature in Next.js that blocks navigation and displays a confirmation pop-up when a user attempts to move to a different page

Is there a way in Next.js to prevent users from navigating to another page and display a confirmation popup instead? If the user clicks "yes," they should be able to continue with the navigation, but if they click "no," they should stay on the current page ...

Error encountered: SQLITE_BUSY - Unable to access the database due to it being locked. This

router.post("/update-quiz", upload.single("file"), async (req, res) => { const transaction = await sequelize.transaction(); try { const actions = { "Multiple Choice": async (questions, transacti ...

Displaying variables in JavaScript HTML

<script type ="text/javascript"> var current = 0; </script> <h3 style={{marginTop: '10', textAlign: 'center'}}><b>Current Status: <script type="text/javascript">document.write(cur ...

Interactive search functionality using jQuery

In the panel I have, I would like to include a search input field that allows users to type in a word. As soon as a match is found, that specific word will be highlighted within the panel while the other information disappears. ...

Using the Google Picker API to dynamically load a file picker when needed

I am interested in integrating the Google Picker API. The provided example demonstrates the picker being loaded upon page load, but I would like the picker to load when a specific action is taken, such as clicking on a button. However, implementing this be ...

Exploring the possibilities of combining CSS classes with Tailwind CSS!

Exploring the integration of Tailwind CSS classes with Next.js for a project I am working on. Is there a method to combine Tailwind CSS classes with Next.js classes? For instance: <img src={user.picture} className="rounded"{styles.pfp}>< ...

What is the best way to move the logo higher and ensure that the <hr> is aligned perfectly with the img

Is there a way to make the logo float up and align with the navigation bar? It seems to be pushed down for some unknown reason. I have tried all the padding tricks that I know, but I also want the image to close the gap on top with the <hr>. So essen ...

To dismiss the Div, simply click on any area outside of it. Leveraging the power of SVG, D3

I need a way to hide my div by clicking outside of it. My SVG has a background and a graph with nodes on top of that. I have a special node (circle) on the graph, clicking on which makes a box appear. To show the box, I use the following code: d3.select ...

issues arise with the website background when inserting an SVG image onto the page

I recently created an svg image with a transparent background using Inkscape. I double-checked to ensure its transparency, and I am confident that it is indeed transparent. However, when I uploaded it to my website, it inexplicably added a white backgrou ...

Is the node exporting any properties?

What is the purpose of assigning some functions as properties of the exports object? Consider this example: exports.index = function(req, res){ res.render('index', { title: 'Hello' }); }; Why utilize exports in this co ...

When consecutive DOM elements are hidden, a message saying "Hiding N elements" will be displayed

Provided a set of elements (number unknown) where some elements should remain hidden: <div id="root"> <div> 1</div> <div class="hide"> 2</div> <div class="hide"> 3</div> <div class="hide"&g ...

Storing a component in browser storage using JavaScript and Angular

I am currently working on developing an Angular application that allows users to "favorite" a business card and store it in local memory. I am facing challenges with actually storing the clicked element in the browser's local memory. Furthermore, I f ...

Switch up the color of the flush list line break in Bootstrap 4

The code snippet taken from the documentation is as follows: <ul class="list-group list-group-flush"> <li class="list-group-item">Cras justo odio</li> <li class="list-group-item">Dapibus ac faci ...

No user was located using Mongoose.findOne()

Utilizing fetch() to make a call to a URL looks like this: const context = useContext(AuthContext); const navigate = useNavigate(); const handleSubmit = (event) => { event.preventDefault(); const dat ...

Ways to include text underneath icons using HTML and CSS

Seeking guidance on how to display text below icons on my website. Can someone please provide instructions? <div class="bottom-bar div-only-mobile" style="position: fixed; bottom: 0; width:100%"> <a href="Dashboard"> <ion-icon name= ...

Discontinuing the fieldset tab interface feature from a Dexterity content type

I am looking to modify a condition to prevent the loading of certain javascript code when inserting an object of my content type. The current condition works only when editing the object: <?xml version="1.0"?> <object name="portal_javascripts"> ...

The ng-disabled directive in AngularJS remains disabled even after the condition is no longer

When utilizing ng-disabled="truthy_scope_variable" to conditionally disable a text input field in AngularJS, an unexpected behavior occurs. The field is disabled the first time the scope variable is turned from truthy to falsified, but subsequent changes d ...

Updating the parent controller's scope from a directive in AngularJS does not reflect changes

HTML: <div ng-app="myApp" ng-controller="Controller"> <test ng-if="toggle" props="condition"></test> </div> Javascript: var myApp = angular.module('myApp', []); myApp.controller('Controller', ['$scop ...

Guide to displaying JSON.stringify data in PHP

I am attempting to retrieve my Google contact list using the Contact API. I have successfully retrieved the result and it is displaying in the console of both Chrome and Firefox browsers. However, I want to print this data using PHP on the same page. < ...

utilizing windows within Javascript

Is there a method to identify and reference a popup window in Javascript or JQuery with a unique name for each window? I am currently creating one variable to open the window, but I am curious if it is possible to attach the 'name' attribute to a ...