Expand or collapse in a sequential manner

Is there a way to ensure that only one table row expands at a time, causing the others to collapse? Any suggestions on achieving this? Here's the HTML code snippet:

<table class="table">
  <tbody>
    <tr class="parent" id="2479">
        <td><span class="btn btn-default">expand</span></td>

    </tr>
    <tr class="child-2479 ">
      <td>row 1</td>
      <td>row 1</td>
      <td>row 1</td>
      <td>row 1</td>
      <td>row 1</td>
      <td>row 1</td>
    </tr>

    <tr class="parent" id="2800">
        <td><span class="btn btn-default">expand</span></td>

    </tr>
    <tr class="child-2800">
      <td>row 2</td>
      <td>row 2</td>
      <td>row 2</td>
      <td>row 2</td>
      <td>row 2</td>
      <td>row 2</td>
</tr>

    </tbody>
</table>

Here is the jQuery code snippet used to achieve this functionality:

$(function() {
    $('tr.parent td span.btn')
        .on("click", function(){
            var idOfParent = $(this).parents('tr').attr('id');
            $('tr.child-'+idOfParent).toggle('slow');
        });
    $('tr[class^=child-]').hide().children('td');
});

Check out the live demo here.

Answer №1

To toggle a specific row, simply click on the desired "child-*" row, hiding all others:

$(function() {
  $('tr.parent td span.btn')
    .on('click', function() {
      var next= $(this).closest('tr').next();   //identifies the row to toggle
      $('tr[class^=child-]').not(next).hide();  //hides all other rows
      next.toggle('slow');                      //toggles the selected row
    });

  $('tr[class^=child-]').hide();
});

Check out the Updated Fiddle

Answer №2

give this a shot

$(document).ready(function() {
    $('tr.parent td span.click-button')
        .on("click", function(){
            var parentId = $(this).parents('tr').attr('id');
            $('tr[class^=child-]').hide().children('td');
            $('tr.child-'+parentId).toggle('slow');
        });
    $('tr[class^=child-]').hide().children('td');
});

Answer №3

See below for the HTML structure:

<table class="table">
    <tbody>
        <tr>
            <td><span class="btn btn-default expandBtn" data-id="2479">expand</span></td>
        </tr>
        <tr class="child-2479 child">
            <td>row 1</td>
            <td>row 1</td>
            <td>row 1</td>
            <td>row 1</td>
            <td>row 1</td>
            <td>row 1</td>
        </tr>

        <tr>
            <td><span class="btn btn-default expandBtn" data-id="2800">expand</span></td>
        </tr>
        <tr class="child-2800 child">
            <td>row 2</td>
            <td>row 2</td>
            <td>row 2</td>
            <td>row 2</td>
            <td>row 2</td>
            <td>row 2</td>
        </tr>
    </tbody>
</table>

Here is the Javascript/jQuery code:

$(document).ready(function() {
    $('.child').hide();
    $('.expandBtn').click(function(){
        $('.child').hide();
        var id = $(this).data('id');
        $('tr.child-' + id).show();
    });
});

For demonstration, you can view the working example on this link.

Answer №4

Here's an alternate approach:

$(function () {
  $('tr.parent td span.btn')
  .on("click", function(e){
    var idOfParent = $(this).parents('tr').attr('id');
    $('tr.child-'+idOfParent).toggle('slow');
    $('tr[class^="child-"]').not('tr.child-'+idOfParent).toggle(false);
  });
  $('tr[class^=child-]').hide();
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<table class="table">
    <tbody>
    <tr class="parent" id="2479">
        <td><span class="btn btn-default">expand</span></td>
    </tr>
    <tr class="child-2479">
        <td>row 1</td>
        <td>row 1</td>
        <td>row 1</td>
        <td>row 1</td>
        <td>row 1</td>
        <td>row 1</td>
    </tr>

    <tr class="parent" id="2800">
        <td><span class="btn btn-default">expand</span></td>

    </tr>
    <tr class="child-2800">
        <td>row 2</td>
        <td>row 2</td>
        <td>row 2</td>
        <td>row 2</td>
        <td>row 2</td>
        <td>row 2</td>
    </tr>

    </tbody>
</table>

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

How to ensure that a div element occupies the entire height of the webpage

After developing a small app in Angular, I'm looking to make the container element expand to the full height of the page, even when the content doesn't fill the entire space. On larger screens, the page doesn't stretch as desired. Here' ...

How can I utilize the Json data retrieved through the findById method in my code?

My current project involves creating an API that retrieves data from Patients (id and name), Physicians (id and name), and Appointments (id, phyId, patId, app_date) in order to display the patients scheduled to see a specific physician. To achieve this, I ...

``The issue concerning the preloading layer on the website``

My experience with the website www.wirecreation.net is sometimes marred by an issue during the initial load. It seems that there is a margin of a few pixels on the gray div containing the logo and progress bar at times, but other times it appears with zero ...

Ways to combine and run the outcomes of several functions with Lodash

Imagine you have two distinct functions (or more) that take one argument from an executor and return the result object. Let's illustrate this with an example: const style_1 = theme => ({ header : { color : theme.primary } }) const sty ...

Exploring ways to retrieve item metadata from a Stripe checkout session

When setting up a Checkout session, I dynamically create prices using the price_data and product_data properties. I include metadata for each item within the product_data.metadata property. However, after a successful payment is made, I retrieve the sessi ...

Ways to verify that a javascript function generates an object and executes a method within that object

Currently, I am in the process of updating server code written in nodejs and incorporating unit tests into the mix. However, I have encountered a challenge that I need assistance with: classX.prototype.methodX = function () { // Create new session ...

Vue Loader: Multiple loaders for a single file extension

Currently, I'm experimenting with incorporating SVG into my vue-loader/webpack template project. I'm in need of loading different types of SVGs: Icons: these are utilized within my components and loaded using svg-inline loader for customizatio ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

Struggling with creating an html file that is responsive on mobile devices

I am currently utilizing bootstrap 4 for the construction of a website. I have encountered an issue where my homepage does not display properly on handheld devices when using Google Chrome's device toggle toolbar. The homepage requires scrolling to vi ...

Exploring AngularJS: A Guide to Accessing Millisecond Time

Is there a way to add milliseconds in Time using AngularJS and its "Interval" option with 2 digits? Below is the code snippet, can someone guide me on how to achieve this? AngularJs Code var app = angular.module('myApp', []); app.controller(&ap ...

Validation for HTML5 does not appear when inputmask is used for entering mobile numbers

One problem that I have encountered is when using the input type = "text" with required = "required" for a mobile number along with an input mask. In this scenario, if a user does not enter any value, the HTML5 validation message does not appear. Instead, ...

Unable to retrieve cookie using getServerSideProps in Next JS

My goal is to retrieve and return two cookies, but I am running into an issue where only the token cookie is returned successfully, while the key cookie remains inaccessible. export async function getServerSideProps(ctx) { const cookies = ctx.req.header ...

Looking to switch up the background color while scrolling, any tips?

I'm trying to change the background color of my navbar section on scroll, but I've had no luck so far. Below is the code I have been using: const [colorChange, setColorChange] = useState(false); const changeColor = () => { if (window.scro ...

What is the best way to allow text input in a table cell to exceed the confines of the table when it is clicked on

I am currently working on a table that has three columns: a label, a dropdown selector, and an input field. The challenge I'm facing is that the input field needs to accommodate multiple lines of content, specifically in JSON format. However, I want ...

Refine the search results according to the value chosen in the select box

After much searching, I still haven't found a satisfactory answer to my query. My goal is to filter search results based on the value selected from a dynamic selectbox populated from a database. The initial select option will be empty, displaying all ...

"Encountered a reference error in Node.js Express due to an undefined

const _expressPackage = require("express"); const _bodyParserPackage = require("body-parser"); const _sqlPackage = require("mssql"); //Initializing the app with the express web framework ...

Organizing Results into Divs Based on Column Value Using AngularJs

I've been racking my brain trying to figure out the best way to organize and display my results in separate divs, specifically using Bootstrap col-md-4's. This is for a chat messaging app that I'm in the process of developing. I have rooms a ...

Retrieving exclusive npm packages from an npmjs user

I am currently facing a challenge with transferring all of our npm modules from npmjs.com to a new location. The issue is that our modules are saved under a private npm user account, making it difficult for me to programmatically access and consume all the ...

Attitude: Defiant and Ignoring Authority

So far, no suggestions have been made, indicating that maybe I haven't properly summarized the issue; The problem arises when I absolutely position the section with the class="container" using an additional class or id specific to that <div>. I ...

Unable to display scrollbar when generating dynamic content with jquery ajax

I have a jQuery report where I am generating dynamic HTML content (nested divs, span, label) using JSON. The report utilizes jQuery, mCustomScrollbar, commons, and jQueryUI. When I have a <div>...//some static code </div>, everything works per ...