Ensuring only one group is open at a time in jQuery when a new group is opened

I need assistance in getting this functionality to work properly. My goal is to have only the clicked group open, while closing all others that are currently open.

Here's a specific example of what I am trying to achieve:

var accordionsMenu = $('.cd-accordion-menu');

if (accordionsMenu.length > 0) {

  accordionsMenu.each(function() {
    var accordion = $(this);
    accordion.on('change', 'input[type="checkbox"]', function() {
      var checkbox = $(this);
      (checkbox.prop('checked')) ? checkbox.siblings('ul').attr('style', 'display:none;').slideDown(300): checkbox.siblings('ul').attr('style', 'display:block;').slideUp(300);
    });
  });
}
<h1>Multi-Level Accordion Menu</h1>

<ul class="cd-accordion-menu animated">
  <li class="has-children">
    <input type="checkbox" name="group-1" id="group-1">
    <label for="group-1">Group 1</label>

    <ul>
      <li class="has-children">
        <input type="checkbox" name="sub-group-1" id="sub-group-1">
        <label for="sub-group-1">Sub Group 1</label>

        <ul>
          <li><a href="#0">Image</a></li>
          <li><a href="#0">Image</a></li>
          <li><a href="#0">Image</a></li>
        </ul>
      </li>
      <li class="has-children">
        <input type="checkbox" name="sub-group-2" id="sub-group-2">
        <label for="sub-group-2">Sub Group 2</label>

        <ul>
          <li class="has-children">
            <input type="checkbox" name="sub-group-level-3" id="sub-group-level-3">
            <label for="sub-group-level-3">Sub Group Level 3</label>

            <ul>
              <li><a href="#0">Image</a></li>
              <li><a href="#0">Image</a></li>
            </ul>
          </li>
          <li><a href="#0">Image</a></li>
        </ul>
      </li>
      <li><a href="#0">Image</a></li>
      <li><a href="#0">Image</a></li>
    </ul>
  </li>

  <li class="has-children">
    <input type="checkbox" name="group-2" id="group-2">
    <label for="group-2">Group 2</label>

    <ul>
      <li><a href="#0">Image</a></li>
      <li><a href="#0">Image</a></li>
    </ul>
  </li>

  <li class="has-children">
    <input type="checkbox" name="group-3" id="group-3">
    <label for="group-3">Group 3</label>

    <ul>
      <li><a href="#0">Image</a></li>
      <li><a href="#0">Image</a></li>
    </ul>
  </li>

  <li class="has-children">
    <input type="checkbox" name="group-4" id="group-4">
    <label for="group-4">Group 4</label>

    <ul>
      <li class="has-children">
        <input type="checkbox" name="sub-group-3" id="sub-group-3">
        <label for="sub-group-3">Sub Group 3</label>

        <ul>
          <li><a href="#0">Image</a></li>
          <li><a href="#0">Image</a></li>
        </ul>
      </li>
      <li><a href="#0">Image</a></li>
      <li><a href="#0">Image</a></li>
    </ul>
  </li>
</ul>
<!-- cd-accordion-menu -->

UPDATE: VIEW WORKING VERSION HERE

CREDIT: @jeto

Answer №1

To implement the functionality shown in your fiddle, consider using a structure like the following:

$(function() {
  $('.cd-accordion-menu input[type="checkbox"]')
    .on('change', function(e) {
      // Retrieve the sibling <li>'s
      var $sameLevelSiblings = $(this).closest('li').siblings();

      // Uncheck the corresponding checkboxes and hide the items
      $sameLevelSiblings.find('input[type="checkbox"]').prop('checked', false);
      $sameLevelSiblings.find('ul').slideUp(300);

      // Display or hide the current items depending on checkbox state
      if ($(this).is(':checked')) {
        $(this).siblings('ul').slideDown(300);
      } else {
        $(this).siblings('ul').slideUp(300);
      }
    })
    // Hide all items on load
    .siblings('ul').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Multi-Level Accordion Menu</h1>

<ul class="cd-accordion-menu animated">
  <li class="has-children">
    <input type="checkbox" name="group-1" id="group-1">
    <label for="group-1">Group 1</label>

    <ul>
      <li class="has-children">
        <input type="checkbox" name="sub-group-1" id="sub-group-1">
        <label for="sub-group-1">Sub Group 1</label>

        <ul>
          <li><a href="#0">Image</a></li>
          <li><a href="#0">Image</a></li>
          <li><a href="#0">Image</a></li>
        </ul>
      </li>
      <li class="has-children">
        <input type="checkbox" name="sub-group-2" id="sub-group-2">
        <label for="sub-group-2">Sub Group 2</label>

        <ul>
          <li class="has-children">
            <input type="checkbox" name="sub-group-level-3" id="sub-group-level-3">
            <label for="sub-group-level-3">Sub Group Level 3</label>

            <ul>
              <li><a href="#0">Image</a></li>
              <li><a href="#0">Image</a></li>
            </ul>
          </li>
          <li><a href="#0">Image</a></li>
        </ul>
      </li>
      <li><a href="#0">Image</a></li>
      <li><a href="#0">Image</a></li>
    </ul>
  </li>

  <li class="has-children">
    <input type="checkbox" name="group-2" id="group-2">
    <label for="group-2">Group 2</label>

    <ul>
      <li><a href="#0">Image</a></li>
      <li><a href="#0">Image</a></li>
    </ul>
  </li>

  <li class="has-children">
    <input type="checkbox" name="group-3" id="group-3">
    <label for="group-3">Group 3</label>

    <ul>
      <li><a href="#0">Image</a></li>
      <li><a href="#0">Image</a></li>
    </ul>
  </li>

  <li class="has-children">
    <input type="checkbox" name="group-4" id="group-4">
    <label for="group-4">Group 4</label>

    <ul>
      <li class="has-children">
        <input type="checkbox" name="sub-group-3" id="sub-group-3">
        <label for="sub-group-3">Sub Group 3</label>

        <ul>
          <li><a href="#0">Image</a></li>
          <li><a href="#0">Image</a></li>
        </ul>
      </li>
      <li><a href="#0">Image</a></li>
      <li><a href="#0">Image</a></li>
    </ul>
  </li>
</ul>
<!-- cd-accordion-menu -->

Note: It's advisable to avoid using HTML elements/attributes directly as selectors; instead, consider utilizing data- attributes for better practice.

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

connect to new database using mysqli_find_cat

<?php $host = "localhost"; $username = "root"; $password = ""; $db = "mineforums"; $connect = mysqli_connect($host, $username, $password, $db) or die(mysqli_error($connect)); ?> Here is the PHP snippet that connects to my databa ...

When I open Firefox, all I see is a blank page with only the h2 heading displayed

I am trying to print the text "I can print" on a page, but only the title shows up and the rest of the page is blank. What mistake might I be making? <!DOCTYPE html> <html> <head> <title>Object exercise 4</title> </head& ...

Transmit data to the controller using an AJAX request

I need to transfer an object from the view page to the controller. Ajax code:-- var jsdata = '{p:' + data + '}'; $.ajax({ type: "POST", url: rootURL + "Deal/Check", contentType: 'application/json; charset=utf-8', da ...

Executing multiple AJAX calls at the same time in PHP

I have a puzzling question that I can't seem to easily solve the behavior of this situation There are two ajax call functions in my code: execCommand() : used for executing shell commands through PHP shell_exec('ping 127.0.0.1 > ../var/log/ ...

Generating pop-up upon loading with CSS3

I have searched through numerous threads and forums in the hopes of finding a solution, but I haven't been successful. My issue lies with triggering a popup on my website. I followed online tutorials to create a popup window, which I was able to do su ...

Tips for enabling browser back and forward functionality in a one-page website design

Building on the previous discussion about optimizing a horizontal sliding layout (Most efficient way to do a horizontal sliding layout), I'm curious if it's feasible to enable the back and forward buttons in the browser when implementing a single ...

Having trouble loading the Google API using getScript. Is displaying a ReferenceError message: "Variable google not found."

I am attempting to dynamically load the Google API using the getScript() method for implementing a "Place Autocomplete Address Form". For more information, you can visit this link: https://developers.google.com/maps/documentation/javascript/examples/places ...

Differences between visibility property manipulation in HTML and JS

One issue I am facing is that when I add a hidden property to a button in the HTML, it remains invisible. <button id="proceed_to_next_question" hidden> Next Question </button> However, if I remove the hidden property and include the following ...

"Encountering a strange issue where submitting a form with Jquery and AJAX in Rails does not work as expected, causing the index

Currently facing a unique issue with a jQuery/Ajax HTML update form. The application in question is a single-page TODO App that utilizes a Rails controller, where all changes to the DOM are made through jQuery/Ajax. After rendering the TODOs on the page v ...

Using Joomla 2.5 and mootools for ajax - passing parameters to a component

After countless hours of searching for a solution to this persistent issue, I find myself stuck with the following code in a standard component along with its controller: defined('_JEXEC') or die; jimport('joomla.application.component.cont ...

Instructions for sending an array of integers as an argument from JavaScript to Python

I have a JavaScript function that extracts the values of multiple checkboxes and stores them in an array: var selectedValues = $('.item:checked').map(function(){return parseInt($(this).attr('name'));}).get(); My goal is to pass this a ...

Having trouble retrieving JSON with crossDomain jQuery AJAX

The process I followed was creating a rails 3.0 scaffold and exposing it using json, keeping it running. When accessing http://localhost:3001/objects.json I can view json data in the browser Next, I had a simple html file with code.jquery.com/jquery-1.7 ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...

Conceal the calendar icon from the date-type HTML input field specifically on the Firefox

The situation at hand is quite straightforward. <input type="date /> When viewed on Firefox (both desktop and mobile), it appears as follows: https://i.stack.imgur.com/S2i0s.png While the internet provides a solution specifically for Chrome: ...

Delete the browsing cache in Internet Explorer from an external source

Currently, I am working on developing an ASP.NET application using Visual Studio. However, a persistent issue I am facing is that every time I launch the application, Internet Explorer caches certain CSS and JS files. This forces me to manually clear the c ...

A table featuring an HTML select element that allows users to choose from preset options or manually enter

My goal is to incorporate a select box where users can either choose from a set list of options or input their own custom value. The select element is nested within a table. Unfortunately, using datalist is not a viable solution for me in this case. I have ...

Troubleshooting issues with applying styles in Vue framework when configured with webpack

I'm facing an issue with setting up the Vue framework using webpack. Specifically, I'm having trouble with styles not being applied when included in the <style> tag within single file components. Despite following several tutorials on this ...

iOS: Incorrect element is currently being scrolled by the user

I encountered an unusual scrolling problem on iOS (7 or 8) while browsing www.cahri.com/tests/scroll How can you replicate this issue? Visit the example page on your iPhone/iPad/iOS Simulator in landscape mode Use your right thumb to touch and scroll th ...

Loading content dynamically into a div from an external or internal source can greatly enhance user experience on a website. By

As I work on my website, I am incorporating a div structure as shown below: <div class="container"> <div class="one-third column"> <a id="tab1" href="inc/tab1.html"><h2>tab1</h2></a> </div> & ...

Combine going to an anchor, performing an AJAX request, and opening a jQuery-UI accordion tab all within a

My goal is to have the user click on the hyperlink below, which will (1) anchor to #suggestions, (2) navigate to the url suggestions.php?appid=70&commentid=25961, and (3) open the jquery-ui accordion #suggestions. However, I am facing an issue where c ...