Creating expandable and collapsible table sections within an HTML document are made possible using

This is an example of code similar to what I am currently working on. I am trying to create collapsible subsections within a table, where the main headers can be opened separately from the subheaders. The goal is for the initial view of the page to display the table with all content collapsed like this: Table with Main Headers & content collapsed

Upon clicking on a main header, I want it to expand and show the associated subheaders and their content in a collapsed state like this: Table Headers clicked with table subheaders collapsed

Lastly, clicking on a subheader should reveal the actual data content like this: Table subheaders clicked with data shown

Currently, I am able to collapse and expand the main headers successfully. However, I am struggling to keep the subheaders collapsed when clicking on the main headers.

Below is my HTML code:

<!DOCTYPE HTML>
<html>
    <head>
        <style> 
            .parent {cursor: pointer; background-color: rgba(234, 118, 86, 1.0);}
            .parent ~ .child {display: none;}
            .open .parent ~ .child {display: table-row;}
            table {border-radius: 5px; margin-bottom: 2em;}
            th {border: solid black; font-size: 28px; border-radius: 10px;}
            td {border: solid black; font-size: 23px; border-radius: 5px; padding: .5em; background-color: rgba(234, 118, 86, 1.0);}
        </style>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>  
        <script src="table.js"></script>
    </head>
    
    <body>
        <table>
            <tbody>
            <tr class="parent"><th colspan="3">Table Section 1</th></tr>
                <tr class="child"><th colspan="3">Table Subsection 1</th></tr>
                    <tr class="child"><th>Name</th><th>Age</th><th>City</th></tr>
                    <tr class="child"><td>Lorem</td><td>Ipsum</td><td>Dolor</td></tr>
                    <tr class="child"><td>Sit</td><td>Amet</td><td>Consectetur</td></tr>
                    
                <tr class="child"><th colspan="3">Table Subsection 2</th></tr>
                    <tr class="child"><th>Name</th><th>Age</th><th>City</th></tr>
                    <tr class="child"><td>Adipiscing</td><td>Elit</td><td>Sed</td></tr>
                    <tr class="child"><td>Do</td><td>Eiusmod</td><td>Tempor</td></tr>
            </tbody>
            <tbody>
            <tr class="parent"><th colspan="3">Table Section 2</th></tr>
                <tr class="child"><th colspan="3">Table Subsection 1</th></tr>
                    <tr class="child"><th>Name</th><th>Age</th><th>City</th></tr>
                    <tr class="child"><td>Incididunt</td><td>Ut</td><td>Labore</td></tr>
                    <tr class="child"><td>Et</td><td>Dolore</td><td>Magna</td></tr>
                    
                <tr class="child"><th colspan="3">Table Subsection 2</th></tr>
                    <tr class="child"><th>Name</th><th>Age</th><th>City</th></tr>
                    <tr class="child"><td>Aliqua</td><td>Ut</td><td>Enim</td></tr>
                    <tr class="child"><td>Quis</td><td>Nostrud</td><td>Exercitation</td></tr>
            </tbody>
        </table>
    </body>
</html>

And here is my JavaScript file:

$(document).ready(function() {
    $('table').on('click', 'tr.parent', function() {
        $(this).closest('tbody').toggleClass('open');
    });
}); // end ready

I have attempted using similar code with the tbody tag and creating a new parent2 class without success. If anyone has any helpful resources or suggestions on how to achieve the collapsing behavior for the subheaders, it would be greatly appreciated!

Answer №1

To implement this functionality, you can utilize JQuery's nextUntil() method:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
    <style> 
        .parent {cursor: pointer; background-color: rgba(234, 118, 86, 1.0);}
        .parent ~ .child, .parent ~ .child2 {display: none;}
        .open .parent ~ .child, .child2.open {display: table-row;}
        table {border-radius: 5px; margin-bottom: 2em;}
        th {border: solid black; font-size: 28px; border-radius: 10px;}
        td {border: solid black; font-size: 23px; border-radius: 5px; padding: .5em; background-color: rgba(234, 118, 86, 1.0);}
    </style>
    <script>
        $(document).ready(function() {
            $('table').on('click', 'tr.parent', function() {
                $(this).closest('tbody').toggleClass('open');
            });
            $('table').on('click', 'tr.child', function() {
                $(this).nextUntil('.child').toggleClass('open');
            });
        }); 
    </script>
    
</head>

<body>
    <table>
        <tbody>
            <tr class="parent"><th colspan="3">Table Section 1</th></tr>
            <tr class="child"><th colspan="3">Table Subsection 1</th></tr>
            <tr class="child2"><th>Name</th><th>Age</th><th>City</th></tr>
            <tr class="child2"><td>Lorem</td><td>Ipsum</td><td>Dolor</td></tr>
            <tr class="child2"><td>Sit</td><td>Amet</td><td>Consectetur</td></tr>
            
            <tr class="child"><th colspan="3">Table Subsection 2</th></tr>
            <tr class="child2"><th>Name</th><th>Age</th><th>City</th></tr>
            <tr class="child2"><td>Adipiscing</td><td>Elit</td><td>Sed</td></tr>
            <tr class="child2"><td>Do</td><td>Eiusmod</td><td>Tempor</td></tr>
        </tbody>
        <tbody>
            <tr class="parent"><th colspan="3">Table Section 2</th></tr>
            <tr class="child"><th colspan="3">Table Subsection 1</th></tr>
            <tr class="child2"><th>Name</th><th>Age</th><th>City</th></tr>
            <tr class="child2"><td>Incididunt</td><td>Ut</td><td>Labore</td></tr>
            <tr class="child2"><td>Et</td><td>Dolore</td><td>Magna</td></tr>
            
            <tr class="child"><th colspan="3">Table Subsection 2</th></tr>
            <tr class="child2"><th>Name</th><th>Age</th><th>City</th></tr>
            <tr class="child2"><td>Aliqua</td><td>Ut</td><td>Enim</td></tr>
            <tr class="child2"><td>Quis</td><td>Nostrud</td><td>Exercitation</td></tr>
        </tbody>
    </table>
</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

Achieving priority for style.php over style.css

Having trouble with theme options overriding default CSS settings in style.css. Here's what I have in my header.php: <link rel='stylesheet' type='text/css' media='all' href="<?php bloginfo( 'stylesheet_url&apo ...

Employing jQuery to redirect to a different URL when a button is clicked

I've been experimenting with a project that involves both JQuery and AJAX. One of the features I have added is JQuery autofill. Here is the code snippet for the form: <form class="form-horizontal"> <div class="form-group"> < ...

Exploring the method of updating functions in Firebase Admin SDK through spying

Is there a way to monitor the update function in Firebase Admin SDK as shown below? yield admin.database().ref('ref').update(obj) I attempted the following without success: const databaseStub = sinon.stub(); const refStub = sinon.stub(); const ...

What is the best way to utilize webpack solely for bundling without using webpack dev server?

Can anyone help me figure out how to use a single server, node.js, to display a react page without using webpack dev server but still bundle code using webpack? Here are the code folders I have: LINK I am working on the server side with node.js/express an ...

Find the average value of an array containing objects

Imagine I have an array of objects like this: const BookDetails = [ { bookName: 'Harry Pottar', readingTime: 10663 }, { bookName: 'Harry Pottar', readingTime: 10986 }, { bookName: 'kaptura Tech', readingTime: 7034 } ] I ...

It seems like the Overflow Hidden feature is not functioning as intended

I'm facing an issue with the overflow:hidden; property not working as expected. My goal is to have multiple inline elements inside a div be cut off at 20 pixels using overflow: hidden; Here's the code snippet: <div class="container"> ...

Why isn't CSS showing up in preview mode on the network tab?

I have been using nextjs for server-side rendering and I am encountering an issue where my CSS class is not being applied on the preview tab, it only works on the client side. Any idea why this is happening? Here is the code snippet: https://codesandbox.io ...

Tips on delivering value each time the increase button is clicked on a dynamically generated input using jQuery

I am currently utilizing jQuery dynamic table inputs within my form. The issue I am facing is that when I select a country from the dropdown, the value is captured correctly. However, if I add another input field dynamically and then select a different cou ...

sending data to Google Maps and updating it

OPERATING SMOOTHLY My requirement is to display only the items that match the entered username and password. I am unable to pass PHP variables to JavaScript in order to query the database and update the map. The following code is functioning correctly (p ...

Accessing Local Data with Local HTML on Android - Error: File Not Found

After organizing my project in a folder within the main root directory, I successfully created a basic hello world project. The HTML file displays perfectly in Chrome, but trying to load files from the main project folder or subfolders results in a net::ER ...

Leverage JavaScript to retrieve the formatting of an element from an external CSS stylesheet

Check out this HTML snippet: <html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> ...

PHP not compatible with Fancybox iframe

I'm facing a simple problem that I can't seem to figure out. I have a button that, when clicked, opens a fancybox with an iframe displaying a page from my website. This page includes a form for sending an email. Everything works fine except that ...

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...

Guide: Utilizing JSON API data to generate marker labels on a leaflet map

Users are presented with points to click on. When a point is clicked, a menu displays text information. I have successfully placed the points, but when attempting to retrieve specific data from the database upon clicking a point, it does not show the marke ...

Adjust div height to match the dynamic height of an image using jQuery

I'm facing an issue with my image setup. It has a width set to 100% and a min-width of 1024px, but I can't seem to get the 'shadow' div to stay on top of it as the window size changes. The height of the shadow div also needs to match th ...

I need to loop through an array of ids and add a new mongodb document for any ids that are missing. What is the best way to ensure that they are saved permanently?

Currently, I am utilizing Node JS and MongoDB to manage a collection of documents containing IDs ranging from 1 to 5000. Nevertheless, there are certain IDs that are absent, and I would like each document to be assigned one unique ID. Below is the snippet ...

Invoking a Components function from a Service in Angular may lead to a potential cyclic dependency issue

I am facing a challenge where I need to call a function from my filterComponent(component) within my engagementService(service). The function in my filterComponent accesses an array that is located within the engagementService. It uses the data from this ...

Developing an interactive contact page using bootstrap technology

I am looking for a way to structure my contact page using Bootstrap. https://i.sstatic.net/e3TCu.png If you're interested, the code for this layout can be accessed here: https://codepen.io/MatteCrystal/pen/xxXpLmK <div class="container" ...

Combining XML files with jQuery

Can multiple XML documents be merged into a single file (named newResult) using jQuery or pure JavaScript? I need to combine various hosted XML documents into one file, for reasons beyond my control. I have tried different techniques but haven't foun ...

Are cookies with the http_only attribute included in requests made through AJAX?

While browsing the web, I came across this interesting link However, it also mentioned at the bottom that This information may no longer be current. This got me thinking, can http_only cookies be transmitted with AJAX? And can AJAX responses set http_only ...