Deselect all child elements when the parent checkbox is not selected

Creating a page that features multiple checkboxes, some nested and others not. When a particular checkbox is selected, additional options will be displayed underneath it for selection; if unchecked, the child boxes will be hidden. Currently, this functionality is achieved solely with CSS. The goal is for checking a parent box to reveal the child options without automatically checking them. The user selects the desired boxes and submits the values, including those in the parent checkboxes. However, when any of the parent boxes are unchecked, the children should also be unchecked. Below is the code snippet for reference.


input {
position: absolute;
left: -9999px;
}

label {
  display: block;
  padding: 15px 30px 15px 15px;
  border: 3px solid #fff;
  border-radius: 100px;
  color: #fff;
  background-color: #6a8494;
  box-shadow: 0 0 20px rgba(0, 0, 0, .2);
  white-space: nowrap;
  user-select: none;
  transition: background-color .2s, box-shadow .2s;
  width: 300px;
}
...
...

Currently, unchecking the first option hides the other checkboxes while they remain visually "checked." Efforts are being made to synchronize the visibility of options with their checked status.

Answer №1

When dealing with jQuery tags, it becomes quite simple. Just include a class in the "additional info" section which we can utilize as a convenient hook positioned next to the original checkbox.

$(document).ready(function(){
$("input[type=checkbox]").on("click", function(){
    // Check if there is a sibling with the additional-info class
    if($(this).siblings(".additional-info").length > 0){
      // If checkbox is unchecked
      if(!$(this).is(":checked")){
        // Uncheck the checkbox
        $(this).siblings(".additional-info").find("[type=checkbox]").prop("checked", false);
      }
    }
})
});
input {
position: absolute;
left: -9999px;
}

label {
  display: block;
  padding: 15px 30px 15px 15px;
  border: 3px solid #fff;
  border-radius: 100px;
  color: #fff;
  background-color: #6a8494;
  box-shadow: 0 0 20px rgba(0, 0, 0, .2);
  white-space: nowrap;
  user-select: none;
  transition: background-color .2s, box-shadow .2s;
  width: 300px;
}

label::before {
  display: block;
  position: absolute;
  top: 10px;
  bottom: 10px;
  left: 10px;
  width: 32px;
  border: 3px solid #fff;
  border-radius: 100px;
  transition: background-color .2s;
}

label:hover, input:focus + label {
  box-shadow: 0 0 20px rgba(0, 0, 0, .6);
}

input:checked + label {
  background-color: #ab576c;
}

input:checked + label::before {
  background-color: #fff;
}

div {
  display: none;
  appearance: none;
  margin: 40px auto 0;
  padding: 5px 40px;
  border: 2px solid #fff;
  color: rgba(0, 0, 0, .8);
  background-color: #9ab593;
  font-family: inherit;
  font-size: inherit;
  font-weight: bold;
  cursor: pointer;
}

#permitted:checked ~ #bodyparts {
  display: block;
}

#neck:checked ~ #direction {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<input id="permitted" type="checkbox">
<label for="permitted" class="side-label">Click to show more options</label>
<div id="bodyparts">
<input id="head" type="checkbox">
<label for="head">head</label>

<input id="neck" type="checkbox">
<label for="neck">neck (click for more options)</label>

<div id="direction" class="additional-info">
<input id="left" type="checkbox">
<label for="left">left</label>

<input id="right" type="checkbox">
<label for="right">right</label>

<input id="both" type="checkbox">
<label for="both">both</label>
</div>

<input id="middle-back" type="checkbox">
<label for="middle-back">middle back</label>

<input id="lower-back" type="checkbox">
<label for="lower-back">lower back</label>
</div>
</section>

Answer №2

Let me demonstrate how to accomplish this task for one section as an example of what needs to be done.

Given the absence of a clearly defined parent-child hierarchy, the solution involves directly referencing elements by their id attributes:

neck.addEventListener('change', () => {
  if (neck.checked) [left, right, both].forEach(el => el.checked = false);
})
input {
  position: absolute;
  left: -9999px;
}

label {
  display: block;
  padding: 15px 30px 15px 15px;
  border: 3px solid #fff;
  border-radius: 100px;
  color: #fff;
  background-color: #6a8494;
  box-shadow: 0 0 20px rgba(0, 0, 0, .2);
  white-space: nowrap;
  user-select: none;
  transition: background-color .2s, box-shadow .2s;
  width: 300px;
}

label::before {
  display: block;
  position: absolute;
  top: 10px;
  bottom: 10px;
  left: 10px;
  width: 32px;
  border: 3px solid #fff;
  border-radius: 100px;
  transition: background-color .2s;
}

label:hover,
input:focus+label {
  box-shadow: 0 0 20px rgba(0, 0, 0, .6);
}

input:checked+label {
  background-color: #ab576c;
}

input:checked+label::before {
  background-color: #fff;
}

div {
  display: none;
  appearance: none;
  margin: 40px auto 0;
  padding: 5px 40px;
  border: 2px solid #fff;
  color: rgba(0, 0, 0, .8);
  background-color: #9ab593;
  font-family: inherit;
  font-size: inherit;
  font-weight: bold;
  cursor: pointer;
}

#permitted:checked~#bodyparts {
  display: block;
}

#neck:checked~#direction {
  display: block;
}
<section>
  <input id="permitted" type="checkbox">
  <label for="permitted" class="side-label">Click to show more options</label>
  <div id="bodyparts">
    <input id="head" type="checkbox">
    <label for="head">head</label>

    <input id="neck" type="checkbox">
    <label for="neck">neck (click for more options)</label>

    <div id="direction">
      <input id="left" type="checkbox">
      <label for="left">left</label>

      <input id="right" type="checkbox">
      <label for="right">right</label>

      <input id="both" type="checkbox">
      <label for="both">both</label>
    </div>

    <input id="middle-back" type="checkbox">
    <label for="middle-back">middle back</label>

    <input id="lower-back" type="checkbox">
    <label for="lower-back">lower back</label>
  </div>
</section>

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

Can you provide step-by-step instructions on how to customize styles with MUI in my application?

I am encountering issues with MUI while attempting to customize the color of my buttons. The two methods I have tried so far have been unsuccessful. For example, Method 1: import React from 'react' import { Typography } from '@mui/material& ...

What is the best way to arrange my crimson blocks to sit next to each other?

Is there a way to align the red boxes side by side with some space in between them for separation, and how can I ensure that the signin/signup button appears against the blue background of the header? I attempted using float but encountered issues. The d ...

Disarrayed image in absolute position on my webpage

I have a website with an auto-resizing background, but I am struggling to have a fixed black bar at the bottom of the page. Everything looks good when the browser window is maximized, but as soon as you scale it down and start scrolling, the black bar alm ...

What is the best way to include attributes in an HTML element?

I've been researching how to dynamically add attributes to an HTML tag using jQuery. Consider the following initial HTML code: <input type="text" name="j_username" id="j_username" autocorrect="off" autocapitalize="off" style="background-image: lin ...

In jQuery, a dropdown selection can be filled with multiple textboxes sharing the same class

I'm experimenting with the idea of using multiple textboxes with the same class filled with different dropdown options that also have the same class. However, I am encountering some issues. When I click on a dropdown option, it changes the value in a ...

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

What is the best way to replicate the orange outline when focused?

I am in the process of creating a series of divs that can be navigated by the user using the tab key. I would like to incorporate the standard orange focus outline for these elements. Is there anyone who can provide guidance on how to achieve this? I unde ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

Encountering null values in IE8/IE7 JavaScript code

Although I am not a JavaScript expert, I have a simple function that works perfectly in all browsers except for IE8 and 7. function setSelected() { var backgroundPos = $('div.eventJumpToContainer').find('.selected').css('backg ...

Using jQuery to make hidden divs visible again

I have a group of products arranged side by side within a div, and I am using a script to hide them one by one. However, at a certain point, all the products have disappeared, and I am struggling to make them re-appear. I've attempted to use .show bu ...

Using Rails and Stripe: Sending out a form and effectively managing errors with AJAX

Lately, I've been struggling with integrating Stripe into my platform. One of the major issues I'm facing is setting up a subscription using AJAX, which I haven't quite cracked yet. On top of that, I need to ensure the credit card informatio ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

Having trouble getting the jQuery/JS redirect button to function properly

I'm fairly new to working with jQuery. My current challenge involves unsetting a cookie and then navigating to the next page. There are numerous resources discussing this topic online, but what seemed like a simple task has turned into a two-hour hea ...

Different approaches to transforming jQuery code into functional AngularJS code

I am a beginner in AngularJS and I'm looking to implement functionality for a login page similar to the one you see when you click the 'Forgot Password' link: Would it be more appropriate to use a directive instead of a controller for this ...

Divs Stacked and Centered

I am currently utilizing the card components from Google's Material Design Lite HTML theme, which can be found at . At the moment, my cards are positioned next to each other and aligned to the left side of the page. I am looking to center the cards o ...

Random Image Generator in Javascript with Links

I am attempting to load one image at a time along with its corresponding link. My goal is to display the image in a div with an ID of 'ads'. Here is the code I have so far, but I am not proficient enough in JavaScript to achieve my desired outcom ...

The key up event in JQuery does not seem to be triggered when selecting the second option in the Select2 plugin's multi

Encountered an issue with the select2 plugin while trying to change the option list based on user input for the second multiple option. The first time I enter text in the multi-select field, the keyup event is triggered and an ajax function is called to b ...

Issue with aligning CSS in Internet Explorer 7

Everything looks great on Firefox and IE8, but on IE 7 the middle "search input text field" is not aligned properly with the other two fields. It seems to be dropping down slightly. Here is the code - thank you for your help: <!DOCTYPE html PUBLIC "-/ ...

Retrieving data from Google Places API in JSON format

Having some trouble with the Places API, I initially attempted to use $.ajax from jQuery but kept encountering an unexpected token error on the first element of the file. It turns out that JSONP cannot be fetched from the Places API. Below is a snippet of ...

Clear all events from an HTML element and its descendants with TypeScript

Each time the page loads, I have HTML from an API that is constantly changing. Is there a way to strip away all events attached to it? The original HTML looks like this: <div id="content"> <h2 onclick="alert('hi');">Test 1< ...