utilizing checkboxes to select multiple occurrences

I have encountered an issue with my script. While it is functioning correctly for a single set of items, I am struggling to make it work with multiple sets. The checkboxes in the first set function perfectly, but I cannot seem to replicate the same behavior for the second and third sets.

$(".checkall").on('change', function() {

                    // all normal checkboxes will have a class "chk_xxxxxx"
                    // where "xxxx" is the name of the location, e.g. "chk_wales"

                    // get the class name from the id of the "check all" box
                    var checkboxesClass = '.chk_' + $(this).attr("id");

                    // now get all boxes to check
                    var boxesToCheck = $(checkboxesClass);

                    // check all the boxes
                    boxesToCheck.prop('checked', this.checked);
                });

                $("#check1 input[type=checkbox], #wales").on("change", function() {
                    checkBoxes();
                });

                function checkBoxes() {

                    $("#checked").empty();
                    if ($("#check1 input[type=checkbox]:checked").length == $("#check1 input[type=checkbox]").length) {

                        $("#wales").prop("checked", true);
                        
                        // Display the id of the "check all" box
                        $("#checked").html($("#checked").html() + "<h3>Wales</h3>");

                    } else {
                        $("#wales").prop("checked", false);
                        $("#check1 input[type=checkbox]:checked").each(function() {
                            $("#checked").html($("#checked").html() + $(this).next().text() + "<br>");
                        });
                    }
                }
            
<!DOCTYPE html>
<html>
<head>

  <meta charset="utf-8">
  <title>Test</title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <!-- <input type="checkbox" id="wales" class="checkall" value="1">
  <label for="wales" >Check All</label>
    <input type="checkbox" id="checkItem1" value="2" class="chk_wales">
    <label for="checkItem1" >Item 1</label>
    <input type="checkbox" id="checkItem2" value="2" class="chk_wales">
    <label for="checkItem2" >Item 2</label>
    <input type="checkbox" id="checkItem3" value="2" class="chk_wales">
    <label for="checkItem3" >Item 3</label>-->

  <hr />
  <input type="checkbox" id="wales" class="checkall" value="1">
<label for="wales">Check All</label>
<section id="check1">
    <input type="checkbox" id="checkItem1" value="2" class="chk_wales">
    <label for="checkItem1">Item 1</label>
    <input type="checkbox" id="checkItem2" value="2" class="chk_wales">
    <label for="checkItem2">Item 2</label>
    <input type="checkbox" id="checkItem3" value="2" class="chk_wales">
    <label for="checkItem3">Item 3</label>
</section>

  <hr />
  <input type="checkbox" id="west" class="checkall" value="3">
  <label for="west">Check All</label>
  <section id="check2">
    <input type="checkbox" id="checkItem4" value="4" class="chk_west">
    <label for="checkItem4">Item 1</label>
    <input type="checkbox" id="checkItem5" value="4" class="chk_west">
    <label for="checkItem5">Item 2</label>
    <input type="checkbox" id="checkItem6" value="4" class="chk_west">
    <label for="checkItem6">Item 3</label>
  </section>
  <hr />

  <input type="checkbox" id="east" class="checkall" value="5">
  <label for="east">Check All</label>
    <section id="check3">
      <input type="checkbox" id="checkItem7" value="6" class="chk_east">
      <label for="checkItem7">Item 1</label>
      <input type="checkbox" id="checkItem8" value="6" class="chk_east">
      <label for="checkItem8">Item 2</label>
      <input type="checkbox" id="checkItem9" value="6" class="chk_east">
      <label for="checkItem9">Item 3</label>
  </section>
<p>You have selected:</p>

<div id="checked">

</div>

</body>
</html>
            

Please can someone provide assistance with this? Your help is greatly appreciated.

Thank you in advance.

Answer №1

discard the checkBoxes() function and update the final event handlers as shown in this example)

//attach the event handler directly to the checkboxes within the section
$( "section input[type='checkbox']" ).on("change", function()
{
    console.log( $( this ) );
    //get reference to the parent section 
    var $parentSection = $( this ).parent();
    //compare the number of checked checkboxes with total number 
    if( $parentSection.find( "input[type='checkbox']:checked" ).length == $parentSection.find( "input[type=checkbox]" ).length )
    {
        $parentSection.prev().prev().prop("checked", true);
        //display checkall's textbox id
        $("#checked").append( "<h3>" + $parentSection.prev().prev().attr( "id" ) + "</h3>");
    }
    else
    {
        $parentSection.prev().prev().prop("checked", false);
        //display text of each checked box
        $parentSection.find("input[type='checkbox']:checked").each(function()
        {
            $("#checked").html($("#checked").html() + $(this).next().text() + "<br>");
        });
    }
});

Answer №2

Here is the code snippet that should meet your needs. I hope this solution proves to be helpful for you.

var checkedDiv = $("#checked");

$('input[type=checkbox]').on('change', function() {
  if (this.className == 'checkall') {
    var section = $(this).nextAll('section:first');
    section.find('input[type=checkbox]').prop('checked', this.checked);
  } else {
    var parentSection = $(this).parent();
    var checkall = parentSection.prevAll(".checkall:first")
    var isEqual = parentSection.find("input[type=checkbox]:checked").length == parentSection.find("input[type=checkbox]").length;
    checkall.prop("checked", isEqual);
  }

  checkedDiv.html('');

  $('.checkall').each(function() {
    if (this.checked) {
      checkedDiv.append('<h3>' + this.id + '</h3><br/>');
    } else {
      var section = $(this).nextAll('section:first');
      section.find("input[type=checkbox]:checked").each(function() {
        checkedDiv.append($(this).next().text() + "<br>");
      });
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="wales" class="checkall" value="1">
<label for="wales">Check All</label>
<section id="check1">
    <input type="checkbox" id="checkItem1" value="2" class="chk_wales">
    <label for="checkItem1">Item 1</label>
    <input type="checkbox" id="checkItem2" value="2" class="chk_wales">
    <label for="checkItem2">Item 2</label>
    <input type="checkbox" id="checkItem3" value="2" class="chk_wales">
    <label for="checkItem3">Item 3</label>
</section>

<hr />
<input type="checkbox" id="west" class="checkall" value="3">
<label for="west">Check All</label>
<section id="check2">
    <input type="checkbox" id="checkItem4" value="4" class="chk_west">
    <label for="checkItem4">Item 1</label>
    <input type="checkbox" id="checkItem5" value="4" class="chk_west">
    <label for="checkItem5">Item 2</label>
    <input type="checkbox" id="checkItem6" value="4" class="chk_west">
    <label for="checkItem6">Item 3</label>
</section>
<hr />

<input type="checkbox" id="east" class="checkall" value="5">
<label for="east">Check All</label>
<section id="check3">
    <input type="checkbox" id="checkItem7" value="6" class="chk_east">
    <label for="checkItem7">Item 1</label>
    <input type="checkbox" id="checkItem8" value="6" class="chk_east">
    <label for="checkItem8">Item 2</label>
    <input type="checkbox" id="checkItem9" value="6" class="chk_east">
    <label for="checkItem9">Item 3</label>
</section>

<p>You have selected:</p>
<div id="checked"></div>

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

Leverage Jasmine for testing a jQuery plugin

I'm currently utilizing the angular-minicolors library () within an angular controller: angular.element("myelement").minicolors({ position: 'top left', change: function() { //custom code to run upon color change } }) Wh ...

Exploring the correlation between aggregation operations in MongoDB and MapReduce techniques

For days, I've been grappling with translating this specific query into MapReduce. My task is to determine the number of different cars that have covered a distance of "N" kilometers. The Query: db.adsb.group({ "key": { "KM": true }, ...

Records are being loaded into the table, but the browser is unresponsive

After making an ajax call, I am receiving over 1000 tr elements for the tbody of a table. However, when I try to load this data into the tbody of the table, Loading the records into the tbody of the table becomes a problem. $('#loadingRecords') ...

Navbar in bootstrap appears to be flashing when it is in its expanded

Example Link On smaller screens, the bootstrap navbar menu does not collapse by default when clicking on a menu item. To fix this issue, I added attributes data-toggle="collapse" and data-target="#navbar-collapse" to each menu item so that the menu will ...

What causes the DOM's appendChild() to trigger on('load', ...) while jQuery's append() does not fire?

I have two snippets of code that I am working with: $(document).ready(function() { document.head.appendChild( $('<script />').attr('src', 'source.js').on('load', function() { ... ...

Exploring IndexedDB with Multi-dimensional Relationships

How do you manage many-to-many relationships in IndexedDB systems? For instance, let's consider a scenario where there is a Blog object to represent a blog post and a Tag object for tagging the posts. A single Blog can have multiple tags, and each ta ...

"Create a dynamic and user-friendly responsive navbar using Bootstrap with toggle

I need assistance with creating a new project template to convert a WordPress template into a Bootstrap template. Currently, I am working on the navbar and facing issues with responsive design and toggle navigation. On laptop devices, the navbar looks goo ...

Endless scrolling results in a full loading rather than a step-by-step one

I'm currently working on implementing infinite scrolling on my website by following a tutorial I came across. However, instead of displaying only a few items at a time and allowing for continuous scrolling, the page loads up with all items at once. I& ...

What steps can I take to avoid the onBlur event from triggering?

I am in the process of developing an input field with a dropdown feature for suggestions. Currently, I have set up an input element that triggers onBlur event to remove the ul element when clicked outside. However, I noticed that clicking on the ul element ...

Modify properties with checkbox selection utilizing AJAX and jQuery

I am facing a challenge in my Task resource where I need to change the boolean attribute based on whether a checkbox is checked or not. Despite having everything set up and working smoothly before adding this AJAX checkbox, including CRUD operations tested ...

Strategies for enabling form resubmission in AngularJS when encountering a Sequelize validation error

Having issues with the form.$valid property in my SignUp controller for user registration. It seems to be stuck at false when a validation error is thrown by Sequelize. Any suggestions on what I should modify in my controller? Perhaps resetting the $vali ...

What is the best way to trigger a mouseup event in Vue when the mouse is released outside of a specific element?

To capture the mousedown event on the element, you can simply add @mousedown. If the cursor is lifted inside the element, using @mouseup will capture the event. However, if the mouse goes up outside of the element (even outside of the browser window), the ...

A guide on updating object values within an array using map in React

Is there a method to calculate the total sum of specific values from an array of objects? Example array: const exampleArray = [ {item_id: 1, quantity: "3"}, {item_id: 2, quantity: "5"}, {item_id: 3, quantity: "2"} ] In this case, I want to add up the qua ...

Ways to conceal the player controls with mediaelementjs.com

Is there a way to display the control bar only when the user hovers over the video while using the mediaelementjs.com player? I feel like there might already be a function for this, but I can't seem to find it anywhere. Should I just implement a simpl ...

Developing Dynamic Key-Driven State Management in ReactJS Using JavaScript

I am facing a challenge with a specific aspect of my ReactJS code, which is more about my comprehension of how JavaScript key/value arrays operate than anything else. How can I allow the key to be passed-in dynamically in the given example? The issue lies ...

Utilizing an HTML time picker for scheduling specific time intervals

Is it possible to use an HTML time picker with a specific interval? https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time According to the link, the step attribute is supported, but I have tested it on the latest versions of Chrome, Edge, ...

Steps to create a hover effect similar to that of a website (increasing grid size on hover)

Looking to create a hover effect for my boxes similar to the one on this website: I've examined the code of the website above and searched extensively for a similar feature without any luck. Could anyone offer assistance with this, please? ...

Can babel 7 deconstruct imports, is it feasible?

Is there a workaround in Babel 7 for exporting modules and deconstructing them using the previous syntax? I'm having trouble achieving the following: // file1.js export const x = 0; export const y = 1; export default z; // file2.js import { x, y } f ...

Modifying the dimensions of an image within a :before pseudo-element

Currently, I am working on designing a mobile menu and encountered an issue with resizing the image of the hamburger menu button. Despite attempting to adjust it by following some suggestions such as this one: How to Resize Image Using CSS Pseudo-elements ...

Checking for the Presence of a Word in a String Using jQuery

I'm currently developing an application that allows users to click on usernames to add them to a reply list. The issue I am facing is that if a user with a similar username is already added, the system mistakenly identifies the new username as already ...