Troubleshooting a JQuery accordion malfunction within a table

I am populating the data dynamically.

However, the Accordion feature is not functioning correctly.

JSFiddle link

http://jsfiddle.net/aff4vL5g/360/

Please note: I am unable to modify the HTML structure.

Current table

Desired output

The first accordion should display child elements upon clicking.

The second accordion should also display child elements upon clicking.

Where could I be making a mistake?

HTML

<table>
    /* first parent */ 
             <tr>
              <td>
                 <a href="#">
                    <div id="accordion"></div>
                 </a>
              </td>
              <td><a href="#">Profit</a></td>
              <td>35%</td>
              <td>22%</td>

           </tr>
    /* first child */ 
           <tr class="parentTR">
              <td></td>
              <td>
                 <a href="#" >
                    <div id="accordion"></div>
                    Business - 1
                 </a>
              </td>
              <td>35%</td>
              <td>22%</td>

           </tr>
    /* second child */ 
           <tr class="parentTR">
              <td></td>
              <td>
                 <a href="#">
                    <div id="accordion"></div>
                    Business - 2
                 </a>
              </td>
              <td>38%</td>
              <td>28%</td>
           </tr>
/* second parent*/ 
             <tr>
              <td>
                 <a href="#">
                    <div id="accordion"></div>
                 </a>
              </td>
              <td><a href="#">Loss</a></td>
              <td>15%</td>
              <td>12%</td>

           </tr>
    /* first child of second parent */ 
           <tr class="parentTR">
              <td></td>
              <td>
                 <a href="#" >
                    <div id="accordion"></div>
                    Business - 1
                 </a>
              </td>
              <td>35%</td>
              <td>22%</td>

           </tr>
    /* second child of second parent */ 
           <tr class="parentTR">
              <td></td>
              <td>
                 <a href="#">
                    <div id="accordion"></div>
                    Business - 2
                 </a>
              </td>
              <td>38%</td>
              <td>28%</td>
           </tr>
        </table>

JQuery

$(function () {
    //  Accordion Panels
    $(".parentTR").hide();
    $("a .accordion ").click(function () {
        $(this).next(".parentTR").slideToggle("slow").siblings(".parentTR:visible").slideUp("slow");
        $(this).toggleClass("active");
        $(this).siblings(".accordion").removeClass("active");
    });
});

Any assistance would be greatly appreciated.

Thank you!

Answer №1

To locate the desired element, you should first navigate to the parent tr and then use .next() to access its sibling.

$(this).closest('tr')
     .next(".parentTR").slideToggle("slow")
     .siblings(".parentTR:visible").slideUp("slow");

Check out this Fiddle for more details

Answer №2

To begin, you must first navigate to the main parent element.

$(function () {
    $(".parentTR").hide();
    
    $("a .accordion ").click(function () {
        $(".parentTR").hide();
        $(this).closest('.main').nextUntil(".main").slideToggle("slow");
       
        $(this).toggleClass("active");
        $(this).siblings(".accordion").removeClass("active");
    });
});

For a working example, check out this Fiddle.

Answer №3

I attempted to solve the issue using this method JSFiddle

HTML :

     <table>
     <tr childTRClass="A1">
      <td>
         <a href="#">
            <div class="accordion"></div>
         </a>
      </td>
      <td><a href="#">Profit</a></td>
      <td>35%</td>
      <td>22%</td>
   </tr>

   <tr class="childTR A1">
      <td></td>
      <td>
         <a href="#" >
            <div class="accordion"></div>
            Business - 1
         </a>
      </td>
      <td>35%</td>
      <td>22%</td>
   </tr>
   <tr class="childTR A1">
      <td></td>
      <td>
         <a href="#">
            <div class="accordion"></div>
            Business - 2
         </a>
      </td>
      <td>38%</td>
      <td>28%</td>
   </tr>

     <tr childTRClass="A2">
      <td>
         <a href="#">
            <div class="accordion"></div>
         </a>
      </td>
      <td><a href="#">Loss</a></td>
      <td>15%</td>
      <td>12%</td>
   </tr>

   <tr class="childTR A2">
      <td></td>
      <td>
         <a href="#" >
            <div class="accordion"></div>
            Business - 1
         </a>
      </td>
      <td>35%</td>
      <td>22%</td>
   </tr>
   <tr class="childTR A2">
      <td></td>
      <td>
         <a href="#">
            <div class="accordion"></div>
            Business - 2
         </a>
      </td>
      <td>38%</td>
      <td>28%</td>
   </tr>

</table>

JQuery:

  $(document).ready(function() {
  $(".childTR").hide();
    $('a .accordion').click(function() {
        var openTRClass = $(this).closest('tr').attr('childTRClass');
               $(".childTR:visible").slideUp("slow");
       $("."+ openTRClass).slideToggle("slow")
               if($('.active').length > 0)
        {
            $('.active').removeClass("active");
        }

        $(this).toggleClass("active");        
    });
});

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

Error message: Metro bundler is unable to access the properties of an undefined object (specifically, 'transformFile')

Having encountered a problem after updating my project to expo SDK 43, I have experimented with different LTS node versions (14.8.1, 16.1.3, and 17.0.1) without success. Interestingly, my colleagues using Macs with Intel chipsets do not face this issue, le ...

Restore the initial content of the div element

Currently, I am utilizing the .hide() and .show() functions to toggle the visibility of my page contents. Additionally, I am using the .HTML() function to change the elements inside a specific div. $('#wrap').html(' <span id="t-image"> ...

AngularJS - automatically submitting the initial item

Is there a simple way to automatically select the first item in my ng-repeat when the list is loaded for the user? Currently, I am using ng-click, but I am unsure of how to automatically trigger a click on the first item. Here is my ng-repeat: <div n ...

Setting up Quill in a Nuxt project (a VUE component)

I'm struggling to remove the toolbar in Quill despite my efforts. This is the HTML snippet I am working with: <template> <quill v-model="content" :config="config"></quill> </template Here's what I have inside the scri ...

Is there a way to access the HTML and CSS source code without using the inspect feature

I'm working on a project that involves an "edit box" where users can write text, add emojis, change the background color, insert images, and more. After users finish creating their content, I want them to be able to send it via email. This means I ne ...

The jQuery CSS menu is having trouble highlighting the active link

Can you help me figure out what's wrong with this code and how I can fix it? I'm working on a CSS menu (horizontal) where I want the background and font to change when an item is selected. I found some jQuery code from another post that should m ...

What is the alternative method of sending a POST request instead of using PUT or DELETE in Ember?

Is there a way to update or delete a record using the POST verb in Ember RESTAdapter? The default behavior is to send json using PUT or DELETE verbs, but those are blocked where I work. I was wondering if there's a way to mimic Rails behavior by send ...

What is the best way to transfer a variable from a Node.js Express server to an EJS HTML file in order to toggle alert visibility?

Hello, I am currently facing a challenge in sending a variable from my app.js file to my ejs HTML file in order to toggle the display of an alert. Here is what the relevant part of my app.js code looks like: view image description here Initially, I attem ...

Retrieving Specific Text Data from Formik Dropdown<option>

I have implemented a reusable Material-UI select component in my project based on the code snippet provided in a tutorial. The SelectWrapper component is used to create a select dropdown with various options: import React from 'react'; import { T ...

Is it possible to prompt npm to install a sub-dependency from a GitHub pull request?

Currently, I'm in the process of setting up geofirestore, which has a dependency on geofirestore-core. However, there is an existing bug in geofirestore-core that has been addressed in a pull request. How can I make sure that my geofirestore installa ...

Guide to creating a dynamically filled dropdown menu with Angular 6 HTML

An array of employees is assigned tests by Lead. When assigning tests, the selected employee is properly assigned. When populating back, Lead can see which test is assigned to which employee. The issue I am facing is that EmployeeID is populated correctly ...

Unable to Define Headers in Fetch GET Call

My current struggle involves sending a GET Request from the browser to my backend (which uses node + express). However, I am encountering issues with setting the headers properly. Below is the code snippet from the frontend: let accessToken = localStorage ...

Using Thymeleaf to display <TR> elements according to specific conditions

Is there a cleaner way to show content only if one object is not null? No annotations found in this block of code. Here is the template: <div th:if="${currentSkills != null}"> <tr ><!-- Data File --> <td class="col_id"> ...

The MVC framework causing the Morris chart to omit the final xkey value

I am facing an issue with my Morris Chart where it is not displaying the last xkey value. Any thoughts on why this might be happening? https://i.stack.imgur.com/mHBQd.png Here is the data I am working with: [{"Date":"2016-07-17","Average":0.0},{"Date":" ...

What is the best way to handle AJAX responses in an onchange event

I'm working on a form where the select option in the input (jurusan) is automatically filled based on the selected value. I need to know how to change the value that appears after selecting an option. For example, if I select option A, it displays th ...

Properly aligning text with checkboxes using HTML/CSS and tags like <span> or <div>

My goal is to have the text displayed as a block in alignment with the checkbox, adjusting based on the sidebar's width. For reference: Current Layout Preferred Layout I have shared the code on CodePen (taking into account screen resolution and wi ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

Merge two JSON arrays without specifying which fields to combine explicitly

After converting two Excel sheets to JSON using an online tool, two separate JSON properties were created for each sheet. The resulting JSON example looks like this: { "Product Info": [ { // Product information details here }, ...

Certain rows in the table should maintain a consistent width, while others are allowed to vary

I am dealing with a table containing certain rows Some of these rows are visible, while others are hidden. The visible rows at the start are referred to as: mainTrs. Clicking on a visible row will make all rows with a class matching its id visible. Cli ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...