The checkbox system is designed so that if all child checkboxes are chosen, the parent checkbox will automatically become selected as well

view image description hereLet's create a checkbox structure with some specific conditions:

  1. When the parent checkbox is selected, all child checkboxes should automatically get selected.
  2. If all child checkboxes are unselected, then the parent checkbox should also get unchecked automatically.
  3. If any single child checkbox is selected, the parent checkbox should get selected as well.

This is how the structure should appear:

Below is my code. However, it doesn't seem to meet the second condition perfectly. The logic seems correct but there might be a syntax issue. Kindly point out the necessary changes or corrections needed. Thank you in advance!

<!DOCTYPE html>
<html>

<head>
    <title>jquery3</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
    <script src="#"></script>
 . . .
    
</body>

</html>

Answer №1

To make selection easier, I suggest adding a class to both the group and child checkboxes. Your parent selector function looks solid, but here's how I would write it. The child selector function should dynamically update based on whether any boxes are checked or not by utilizing the .length property to count the number of checked child boxes. Check out this Jsfiddle for reference.

$(document).ready(function() {
  // Check/uncheck all siblings
  $('.selector input.parent-check').click(function() {
    $(this).closest("div.check-group").find(".child-check").prop("checked", this.checked);
  });

  // Check/uncheck parent based on children
  $('.selector input.child-check').click(function() {
    var numChecked = $(this).closest("div.check-group").find(".child-check:checked").length;
    $(this).closest("div.check-group").find(".parent-check").prop("checked", (numChecked > 0));
  });
});

Answer №2

You made two mistakes:

  1. The line
    var is_checked = $(checkbox).is(':checked');
    did not return the correct value. You could have simply used checkbox.is(':checked'); instead of defining 'is_checked'.
  2. Instead of using .removeAttr() in
    $(checkbox).parents("ul").siblings("div").find('.parchek').removeAttr('checked');
    , you should have used .prop('checked', false);

Here is the corrected code:

$(document).ready(function() {
  $('.parchek').click(function() {
    $(this).parents().siblings("ul").find("input").prop('checked', this.checked);
  });

  $('.selecter').find('input').each(function(index, input) {
    $(this).on("change", function() {
      var checkbox = $(this);
      var is_checked = checkbox.is(':checked');

      if (is_checked) {
        $(checkbox).parents("ul").siblings("div").find('.parchek').prop('checked', this.checked);
      } else {
        let checkboxes = $(this).parents("ul").find("input");
        
        if (allCheckBoxesUnChecked(checkboxes)) {
          $(checkbox).parents("ul").siblings("div").find('.parchek').prop('checked', false);
        }
      }
    });
  });

  // helper function that checks if all checkboxes are unchecked
  function allCheckBoxesUnChecked(elems) {
    let allUnchecked = true;
    $.each(elems, function(ind, item) {
      if (item.checked) {
        allUnchecked = false;
        return;
      }
    });
    return allUnchecked;
  }
});
.col-md-3.mx-auto.my-3.d-block.px-0 {
  border: 1px solid;
  border-color: #eeeeee;
}

.col-md-3.mx-auto.my-3.d-block .header {
  background: linear-gradient(#f1f1f1, #fff);
  border-bottom: 1px solid #eeeeee;
  color: #616161;
  letter-spacing: 1px;
  padding-top: 2px;
  padding-left: 18%;
  font-family: Georgia;
  font-weight: bold;
  /* height: 9%; */
  padding-bottom: 2px;
}

.col-md-3.mx-auto.my-3.d-block .Drop-down {
  padding-top: 4%;
  padding-left: 6%;
}

.col-md-3.mx-auto.my-3.d-block .Drop-down .drop-down {
  background: #fff;
  border: 2px solid #f1f1f1;
  font-size: 15px;
  /* padding-left: 18%; */
  font-family: Georgia;
}

.col-md-3.mx-auto.my-3.d-block .selecter {
  padding-top: 4%;
  padding-left: 6%;
  color: #464f44;
  font-size: 15px;
  /* padding-left: 18%; */
  font-family: Georgia;
}

#submitbtn {
  margin-top: 4%;
  margin-left: 6%;
  margin-bottom: 4%;
  /* height: 23px; */
  width: 72px;
  background: linear-gradient(#fff, #f1f1f1);
  /* font-size: 13px; */
  font-family: Georgia;
}

.OU {
  margin-bottom: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>jquery3</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
...
... Remaining HTML code truncated for brevity ...
...
</body>
</html>

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

Exploring the Sidebar Navigation Features of Bootstrap 4

Looking to incorporate a vertical navigation menu on the left side of my webpage, extending the full height of the page. My attempt to achieve this using the Bootstrap grid system resulted in the navigation menu becoming too wide. This issue persisted eve ...

Designing HTML Emails Using Nested Tables

Why is my text-decoration="none" not displaying properly? I have tried placing it in various locations like table, tr, td, but I am unable to make it work. Are there any common mistakes when styling email designs? Here is the code snippet: <table cel ...

Limit access to a page only to designated users

Having a challenge creating a secure page for band members to access their individual band pages. In the band table, each band has four columns labeled $bandm1, $bandm2, $bandm3, and $bandm4. I attempted to create a script that extracted the session user ...

Each time the web animation is utilized, it gets faster and faster

As part of an assignment, I am working on creating an interactive book that can be controlled by the arrow keys and smoothly comes to a stop when no key is being pressed. However, I have noticed that with each arrow key press, the animation speeds up. Bel ...

Finding the desired value from an option select in a JSON object is key

Looking to parse data from the option value. Specifically interested in extracting either the ID or UserName. Can anyone offer some guidance? $(document).ready(function() { $.getJSON("http://localhost:8080/EBCargoAndCommodityServices/resources/user-fo ...

Angular material chips showcase a row of five chips

I am working with the basic mat-chips from angular material and I want to arrange them in rows of five without increasing their size: Chip1 Chip2 Chip3 Chip4 Chip5 ..................(space left) Chip6 Chip7 Chip8 Chip9 Chip10 ...............(space le ...

When a parent document is deleted, Mongoose automatically removes any references to child documents

Greetings everyone, thank you for taking the time to read my query. I am looking to remove a child object that is referenced in a parent object. Below is the structure: const parentSchema: = new Schema({ name: String, child: { type: mongoose.Schema. ...

Using a combination of jQuery and AJAX to send data via a form

I've been working on a script to create a popup form that, once submitted, should trigger another function to send the data via ajax. However, I'm facing an issue where the second function isn't being activated. Can someone spot what's ...

What is the best way to display an additional component upon logging out in a React application that utilizes

Is there a way to render a different component when logging out of firebase? I am attempting to refresh the page to display the LoginPage. Here is my LoginPage that is shown when logging in with a different form. import React, { Component } from "react" ...

Pass back the jQuery deferred object from the error section of an Ajax request

I am facing a challenge with loading a file using jQuery Ajax. When the initial location fails, it should attempt to retrieve it from another path. Although the request redirects to the alternate URL, I am not receiving the necessary jQuery deferred from l ...

How to best handle dispatching two async thunk actions in Redux Toolkit when using TypeScript?

A recent challenge arose when attempting to utilize two different versions of an API. The approach involved checking for a 404 error with version v2, and if found, falling back to version v1. The plan was to create separate async thunk actions for each ver ...

Guide on adding a parent class to style all generated CSS rules in styled-components 5.3.5

When my application loads into a parent div with a specific class (for example, .my-app), is there a way to add the prefix .my-app to all classes generated by styled-components? For instance, consider a component like this: import React from 'react& ...

Efficiently storing multiple file fields in Django with the help of jQuery and Ajax

I need assistance with saving multiple file fields to a server. The fields are dynamic, allowing users to upload as many files as they want using an add button. I prefer not to use form submit or dropzone. Can someone please advise me on how to achieve thi ...

useEffect runs endlessly

Currently, I am using React with hooks to handle API calls and implement autoscroll functionality on a data-heavy screen. However, I have encountered a problem where the autoscroll feature implemented through a separate useEffect is interfering with the ot ...

Does the syntax for the $.ajax() function appear to be incorrect in this instance?

I am attempting to use .ajax to retrieve the source HTML of a specific URL (in this case, www.wikipedia.org) and insert it into the body of a document. However, the code provided below is not producing the expected outcome. <!DOCTYPE html> < ...

What are the best practices for securely using JSON.stringify in JavaScript?

When I use JSON.stringify on a string that includes <script> tags, the script tags somehow escape and show up in the body of my document, causing unexpected results with the "injected" data. I'm puzzled by how they manage to escape, considering ...

Neglecting the Outcome of Async/Await

I am facing an issue where I need to send different SMS messages to different recipients synchronously, but my current implementation using async/await is not producing the expected results. Below is the code snippet causing the problem: Upon querying fo ...

Substitute the temporary text with an actual value in JavaScript/j

Looking to customize my JSP website by duplicating HTML elements and changing their attributes to create a dynamic form. Here is the current JavaScript code snippet I have: function getTemplateHtml(templateType) { <%-- Get current number of element ...

What is the method for setting the current time as the default in a time picker?

Below is a snippet of code where I attempt to implement a date picker and set the current time as the default value. .HTML <input type="time" [(ngModel)]="time"> .TS time; constructor() { this.time= new Date(); } ...

Securing AJAX Requests: Encrypting GET and POST Requests in JavaScipt using Node.js

Looking for a way to secure ajax post and get requests using JavaScript. The process would involve: Server generates private and public key upon request Server sends the public key to client Client encrypts data with public key Server decrypts data wit ...