I am interested in creating a table that can toggle between show/hide mode with a plus/minus feature

 $(document).ready(function() {
        $("#t1").hide(); // hide table by default
        $("#close").hide(); //hide the minus button as well if you only want one button to display at a time

  $('#sp1').on('click', function() { //when plus button is clicked
    $("#t1").show(); 
    $("#sp1").hide(); //you need to hide the plus button now
    $("#close").show(); //and then display the minus button
  });
  $('#close').on('click', function() { 
    $("#t1").hide(); //hide table
    $("#close").hide(); //hide minus btn
    $("#sp1").show(); //show plus button
  });
});
 $(document).ready(function() {
  $("#t2").hide(); // hide table by default
  $('#sp2').on('click', function() {
       toggleButtons(true);
    $("#t2").show();
  });
  $('#close2').on('click', function() {
       toggleButtons(false)
    $("#t2").hide();
  });
      function toggleButtons(show) {
      if (show) {
        $("#sp2").hide();
        $("#close2").show();
      } else {
        $("#sp2").show();
        $("#close2").hide();
      }
  }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" rel="stylesheet"/>
<link href="https://pro.fontawesome.com/releases/v5.10.0/css/fontawesome.css" rel="stylesheet"/>

<div class="col-md-12 col-12 table-responsive">
  <div class="form-group">
    <div class="col-md-12" style="padding: 10px !important;" align="center">
      <div class="form-group">Main heading</div>
    </div>
<table class="table table-hover">
      <thead class="lbbg3">
        <tr>
          <td style="width: 800px;">Sub heading 1</td>
          <td>Sub heading 2</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th style="background: #eef7fc; text-align: left;" colspan="2">
            <button class="table-plus-btn table1" id="sp1"><i class="fa fa-plus"></i></button><button class="table-minus-btn" id="close"><i class="fa fa-minus"></i></button> Child Heading
          </th>
        </tr>
        <tr>
          <td colspan="2">
            <div class="table1shw">
              <table class="table1 table-hover" id="t1">
                <tr>
                  <td style="text-align: left; width: 800px;">
                    Row 1
                  </td>
                  <td style="text-align: center;">
                    <div class="custom-control custom-radio radio-table">
                      <a href="#doc">
                        <input type="radio" id="customRadio50" name="customRadio" class="custom-control-input fcy edu docbtn" />
                        <label class="custom-control-label" for="customRadio50" style="cursor: pointer;" onchange="valueChanged()"></label>
                      </a>
                    </div>
                  </td>
                </tr>
                <tr>
                  <td style="text-align: left; width: 800px;">
                    Row 2
                  </td>
                  <td style="text-align: center;">
                    <div class="custom-control custom-radio radio-table">
                      <input type="radio" id="customRadio51" name="customRadio" class="custom-control-input fcy" />
                      <label class="custom-control-label" for="customRadio51" style="cursor: pointer;"></label>
                    </div>
                  </td>
                </tr>
              </table>
            </div>
          </td>
        </tr>
           <tr>
          <th style="background: #eef7fc; text-align: left;" colspan="2">
            <button class="table-plus-btn table1" id="sp2"><i class="fa fa-plus"></i></button><button class="table-minus-btn" id="close2"><i class="fa fa-minus"></i></button> Child Heading2
          </th>
        </tr>
        <tr>
          <td colspan="2">
            <div class="table1shw">
              <table class="table1 table-hover" id="t2">
                <tr>
                  <td style="text-align: left; width: 800px;">
                    Row 3
                  </td>
                  <td style="text-align: center;">
                    <div class="custom-control custom-radio radio-table">
                      <a href="#doc">
                        <input type="radio" id="customRadio50" name="customRadio" class="custom-control-input fcy edu docbtn" />
                        <label class="custom-control-label" for="customRadio50" style="cursor: pointer;" onchange="valueChanged()"></label>
                      </a>
                    </div>
                  </td>
                </tr>
                <tr>
                  <td style="text-align: left; width: 800px;">
                    Row 4
                  </td>
                  <td style="text-align: center;">
                    <div class="custom-control custom-radio radio-table">
                      <input type="radio" id="customRadio51" name="customRadio" class="custom-control-input fcy" />
                      <label class="custom-control-label" for="customRadio51" style="cursor: pointer;"></label>
                    </div>
                  </td>
                </tr>
              </table>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Hello, I'm having trouble figuring out how to display only one table when I click on the plus button. Right now, both tables are opening simultaneously. I want to show one at a time and close the other when I open a new one. I've successfully implemented this using an accordion before, but I'm struggling here. Can someone please assist me with this issue?

Answer №1

If you're utilizing bootstrap, it's essential to enhance the reusability and readability of your code. While you've done a good job overall, consider restructuring your code for better efficiency. I took the liberty to rewrite a portion of your code as an example (hiding all elements before displaying the clicked one)... parsing through yours seemed like too much effort.

$(document).ready(function() {
        $(".allcontent").hide(); // default table hidden
        $(".hide").hide(); // hide minus button if only one display at a time
        
        $('.show').on('click', function() {
          $('.allcontent').hide();
          $('.show').show();
          $('.hide').hide();
          $(this).parent().find('.show').hide();
          $(this).parent().find('.hide').show();
          $(this).parent().parent().find('.allcontent').show();
        });

        $('.hide').on('click', function() {
          $(this).parent().find('.show').show();
          $(this).parent().find('.hide').hide();
          $(this).parent().parent().find('.allcontent').hide();
        });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="main-container">

  <div class="1st">
  
    <div class="2nd">
      <button class="show">
        +
      </button>
      <button class="hide">
        -
      </button>
    </div>

    <table class="table1 table-hover allcontent">
      <tr>
        <td style="text-align: left; width: 800px;">
         Row 1
        </td>
        <td style="text-align: center;">
          <div class="custom-control custom-radio radio-table">
            <a href="#doc">
             <input type="radio" id="customRadio50" name="customRadio" class="custom-control-input fcy edu docbtn" />
            <label class="custom-control-label" for="customRadio50" style="cursor: pointer;" onchange="valueChanged()">
            </label>
           </a>
         </div>
        </td>
      </tr>
      <tr>
        <td style="text-align: left; width: 800px;">
         Row 2
        </td>
        <td style="text-align: center;">
          <div class="custom-control custom-radio radio-table">
            <input type="radio" id="customRadio51" name="customRadio" class="custom-control-input fcy" />
            <label class="custom-control-label" for="customRadio51" style="cursor: pointer;">
            </label>
          </div>
        </td>
      </tr>
    </table>
    
  </div>
  
  <div class="1st">
  
    <div class="2nd">
      <button class="show">
        +
      </button>
      <button class="hide">
        -
      </button>
    </div>
    
    <table class="table1 table-hover allcontent">
      <tr>
        <td style="text-align: left; width: 800px;">
          Row 3
        </td>
        <td style="text-align: center;">
          <div class="custom-control custom-radio radio-table">
            <a href="#doc">
              <input type="radio" id="customRadio50" name="customRadio" class="custom-control-input fcy edu docbtn" />
              <label class="custom-control-label" for="customRadio50" style="cursor: pointer;" onchange="valueChanged()"></label>
            </a>
          </div>
        </td>
      </tr>
      <tr>
        <td style="text-align: left; width: 800px;">
          Row 4
        </td>
        <td style="text-align: center;">
          <div class="custom-control custom-radio radio-table">
            <input type="radio" id="customRadio51" name="customRadio" class="custom-control-input fcy" />
            <label class="custom-control-label" for="customRadio51" style="cursor: pointer;"></label>
          </div>
        </td>
      </tr>
    </table>
    
  </div>
  
</div>

EDIT:

To improve efficiency, think about adding an 'active' class to the algorithm. Currently, the code functions in the following manner:

  1. A button is clicked.
  2. All collapsible elements are retrieved.
  3. All elements are hidden.
  4. The clicked element is shown.

A small adjustment to the algorithm could involve adding an 'active' class. This would eliminate the need to iterate through all items. The revised procedure would look like this:

  1. A button is clicked.
  2. The active element is identified, the 'active' class is removed, and it is hidden.
  3. The 'active' class is added to the new element, and it is displayed.

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

Ensure Your Forms Are Error-Free with Jquery Form Validation

Currently working on a registration form that involves the use of credit cards. I have reached the stage of form validation to ensure that users input correct data in the appropriate fields. However, this has led me to ponder whether relying on JQuery for ...

The onChange event of the dropdownlist in MVC is not functioning correctly and is not properly triggering the action

Hey everyone, I'm trying to achieve a functionality where changing the selection of a dropdown list will trigger an AJAX call to a specific action with some data being passed. Below is the code I have implemented for this purpose. Despite verifying th ...

Positioning tooltip arrows in Highcharts

I'm attempting to modify the Highcharts tooltip for a stacked column chart in order to have the arrow on the tooltip point to the center of the bar. I understand that I can utilize the positioner callback to adjust the tooltip's position, but it ...

Implementing a Context Menu with a Single Click

I need assistance with creating a context menu that appears when the user clicks inside an HTML5 canvas. I want to have functions called when an item in the menu is selected. Can anyone provide guidance on how to achieve this? ...

"Enhance Your Website with jQuery: Organized Lists with Fixed Length, Connected,

I currently have a list that is separated into three columns, structured as follows: Column1 Column2 Column3 1 4 7 2 5 8 3 6 9 The list ranges from 1 to 9 and each column consists of a fixed number of rows (3). I am lo ...

CSS: Troubles with Element Widths

I'm dealing with a list item that contains an image, like so: <ul> <li> <img></img> </li> </ul> The image is not filling the entire width of the list item. Is there a way to make the list item shr ...

How can I resolve the issue of React not identifying the prop on a DOM element?

Currently, I am learning React and facing an issue with a warning message: "react-dom.development.js:86 Warning: React does not recognize the isSelected prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell i ...

The module in the relative path cannot be located by Node.js

Node.js is giving me some trouble with exporting and importing classes from multiple files. In one file, I have two classes that I'm exporting using the following code: module.exports = {TrigInter, Hilbert}; However, when I try to import these classe ...

Unique phrase: "Personalized text emphasized by a patterned backdrop

I'm facing a challenge and struggling to find a way to highlight text using CSS or jQuery. My goal is to have an image on the left, another one on the right, and a repeated image in between. Since there are some long words involved, I need a dynamic s ...

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...

Tips for positioning an advertisement at the center of a full-screen HTML5 game

I am struggling to find a way to perfectly center my advertisement in a fullscreen HTML5 game. The game automatically expands to fullscreen when played, and I want the advertisement to always be positioned in the center, regardless of whether the game is b ...

"Cascading Style Sheets for Organizing Buttons in a Grid

I have created a layout in Word that I want to achieve: https://i.stack.imgur.com/krK7w.png After researching, I found out about the CSS grid layout which seems like the best option for achieving the desired layout. However, when implementing the grid i ...

Data in DynamoDB Local is deleted once the instance is shut down

My app is utilizing DynamoDB Local and I am facing an issue where it keeps deleting all the sample data each time I shut down the instance. This problem seems to be unique as I have not found any similar cases while searching for a solution. I typically ...

Ways to break apart a string of text without a regular pattern

Here is the data I am working with: Huawei Y7P Art-L28 (4/64gb) (AAAAAAAAAAAAAA) EXP:02/19/2020 Huawei Y9 prime 2019 (BBBBBBBBBBBBBBB) EXP:07/17/2019 Oppo A31 4gb/128gb (CCCCCCCCCCCCCCC) Vivo Y15 5000mah 4GB/64GB (1901) (DDDDDDDDDDDDDDD) EXP:06/14/2019 I ...

Utilizing the Bootstrap grid system allows for input fields to automatically expand to 100% width once they reach

I am encountering some challenges while attempting to develop a responsive form using bootstrap grids. The issue seems to arise when resizing the browser window, as the grid classes behave unexpectedly by expanding and taking up the entire page width at ce ...

What is the best way to augment an AJAX array response with additional data?

I'm working on an AJAX request and I need to add additional properties to the response I receive. Can anyone offer some guidance? Here is the AJAX request code I'm using: var form_data = {}; $.ajax({ type: "GET", url: "../../../sample_ ...

When combining AJAX with PHP and HTML, one limitation to note is that PHP alone cannot generate or create the file

I am facing a particular problem here. Currently, I am using HTML with AJAX: <html> <head> <script> function ajax_post(){ // Create our XMLHttpRequest object var hr = new XMLHttpRequest(); // Create some variables we need to ...

<div> issues with background display

I have created two different sections with distinct backgrounds. However, I am facing an issue where these two divs are not appearing on the webpage. My intention is to position the Navbar at the top and have another section below it that is not linked to ...

Creating a new form upon clicking

By clicking the "Add New Job" link, a new form with three fields will appear. This is the primary form: <h2>JOB EXPERIENCE 1</h2> <div class="job-content"> <input type="text" value="Company" name="company" /> <input type="te ...

The AJAX response consistently returns a 405 status code

I am experiencing an issue with an AJAX post request. $.ajax({ type: "POST", contentType: "application/json", url: "/rating/save", data: JSON.stringify(rating), dataType: "json", mimeType: "application/json" ...