Struggling to toggle the visibility of a table with a button - successfully hiding it, but unable to make it reappear?

I need a button that can toggle (show/hide) a table. Currently, my code hides the table successfully, but it fails to show the table again when I click the button. It seems like there is an issue with refreshing or redirecting after clicking the button for the second time. I suspect that the file might be lost causing the table not to appear again. Here's the snippet of my code:

class TableCsv {
  /**
   * @param {HTMLTableElement} root The table element which will display the CSV data.
   */
  constructor(root) {
    this.root = root;
  }

  // More class methods here

}

const tableRoot = document.querySelector("#csvRoot");
const csvFileInput = document.querySelector("#csvFileInput");
const tableCsv = new TableCsv(tableRoot);

// Event listener and function for handling table visibility
function hidefunction() {
  let x = document.getElementById('csvRoot');
  if (x.style.visibility === "hidden") {
    x.style.display = "visible";
  }
  x.style.display = "hidden";
}
table {
  // CSS styles for the table
}

th {
  // CSS styles for table header cells
}

// Additional CSS styles
<!DOCTYPE html>
<html lang="en">

<head>
  <!-- head elements -->
</head>

<body>
  <section class="hero is-fullheight">
    <!-- hero section content -->
  </section>

  <h1 style="text-align: center">
    Budgeting made easy
  </h1>

  <div class="tabs">
    <div class="tab-2">
      <label for="tab2-1">Budget Tool</label>
      <input id="tab2-1" name="tabs-two" type="radio" checked="checked">
      <div>
        <h2 style="text-align: center">Let's Get Started</h2>
        <form action="/">
          <div class="btn btn-primary btn-file">
            <label for="csvFileInput" style="text-align: left">Select a file:</label>
            <input type="file" id="csvFileInput" style="cursor: pointer; padding-bottom: 30px">
            <table id="csvRoot"></table>
            <button type="submit" onclick="hidefunction()">Hide table</button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- More tab content here -->

  </div>

  <script src="path/to/other/js/files.js"></script>

</body>

</html>

Answer №1

As mentioned by @User123, it is important to use the correct values for the following:

style.display should be either none or block

style.visibility should be either hidden or visible

I have made adjustments to the structure of the if..else blocks in order to properly hide and show the table as requested.

A new function removeFunction() has been added to illustrate the difference between removing an element and hiding it. Setting style.display:none will remove the element from the page and shift the contents accordingly. On the other hand, using style.visibility:hidden will keep the element in place without any movement but make it invisible.

In response to the issue with the button causing a strange refresh behavior due to being a submit button, I have changed its type to button.

Here is a brief demonstration of the code:

function hideFunction() {
  let element = document.getElementById('csvRoot');
  if (element.style.visibility === "hidden") {
    element.style.visibility = "visible";
  } else {
    element.style.visibility = "hidden";
  }
}

function removeFunction() {
  let element = document.getElementById('csvRoot');
  if (element.style.display === "none") {
    element.style.display = "block";
  } else {
    element.style.display = "none";
  }
}
table {
  display: block;
  visibility: visible;
}
<table id="csvRoot">
  <thead>
    <th>2010</th><th>2011</th><th>2012</th>
  </thead>
  <tr>
    <td>112</td><td>321</td><td>411</td>
  </tr>
  <tr>
    <td>131</td><td>133</td><td>331</td>
  </tr>
  <tr>
     <td>331</td><td>133</td><td>131</td>
  </tr>

</table>
<button type="button" onclick="hideFunction()">Hide/Show Table</button>
<button type="button" onclick="removeFunction()">Remove/Replace Table</button>

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

Having trouble with deploying Node.js to Heroku? Feel like your 'git push her

After successfully running my app locally, I encountered an issue when trying to deploy it to Heroku. The deployment process just hangs indefinitely and only displays one public file on the website with an error message stating: "https://analogy-alley.hero ...

Directives and Transclusion: A Comprehensive Guide

I am currently working on creating navigation directives to simplify complexity. My goal is to have the following HTML structure for my navigation: <custom-nav> <nav-item>Item 1</nav-item> <nav-item>Item 2</nav-item> ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

When running the command `npx create-react-app client`, an error is thrown stating "Reading properties of undefined is not possible (reading 'isServer')."

Installing packages. Please wait while the necessary packages are being installed. Currently installing react, react-dom, and react-scripts with cra-template... Encountered an error: Unable to read properties of undefined (reading 'isSer ...

Bot in discord.js refuses to exit voice channel

I've been struggling to get my bot to leave the voice channel despite trying multiple methods. Here's what I've attempted in the source code: Discord.VoiceConnection.disconnect(); Although this is the current code, I have also tested: messa ...

Retrieve the user's IP address from the request rather than Cloudflare's IP address

Cloudflare alters the IP addresses of incoming requests as it acts as a middleman between my website and the Internet, functioning as a proxy. Is there a way to retrieve the original IP address of the request, rather than Cloudflare's IP address? I h ...

Is there a way for me to implement this code to achieve the functionality shown in the demo link

$('select').change(function() { var sum = 0; var sum = parseInt($('select[name="bathrooms"]').val() * 25) + parseInt($('select[name="bedrooms"]').val() * 8); $("#sum").html(sum); }); <script src="https://ajax.googleap ...

Ways to troubleshoot CORS issue while working with pseudo API?

While utilizing a mock API, I encountered the familiar error message: "No 'Access-Control-Allow-Origin' header is present on the requested resource.". Despite watching videos and reading articles on this issue, the solutions provided we ...

Strategies for Connecting CSS, JavaScript, and Image Files in Django

Being new to Django 1.9.5 and working on Windows, I am facing difficulty in linking my CSS, images, and JS files to the Django template. This is how my project structure looks like: Here is my settings page: BASE_DIR = os.path.dirname(os.path.dirn ...

Switching markdown data into HTML within a Django and React application

I am considering the best way to store blog content in my database so that I can easily display it on an HTML page using an AJAX call. After conducting research, I have found suggestions to store the blog post as markdown, which seems logical since it supp ...

After applying the rotateY function, the z-index appears to be malfunctioning

My current project involves creating a page flip effect, which requires two overlapping div elements. Initially, both divs are side by side with the second div having a -webkit-translateY(180deg) property applied to it. The first div has a z-index of 2, wh ...

Hover background color not being applied to child elements within Button element in Firefox

Ensuring that my product is SEO-friendly, I incorporated semantic markup using the button element and schema attributes. To separate individual items, I utilized "span" elements while setting hover effects on selected items by adding display:block. This a ...

When you click on the Admin Panel Side menu, the page refreshes instead of expanding the menu item

I have encountered a strange problem with the AdminLTE admin panel template that I am using in my Angular 11 application. Everything is loading fine with the menu items, but when I click on an item, instead of expanding the group, the page refreshes. Here ...

Exploring Azure: Obtain a comprehensive list of application settings from a deployed Node.js web application

After successfully deploying a NodeJs app to a Linux Azure AppService, I am now aiming to retrieve the server settings of this particular app-service. By enabling managed Identity for the AppService under the 'Identity' tab, I attempted to achiev ...

PHP script for batch string replacement

My function is triggered by a button click, where it takes two input IDs and forms a string as follows: var str = "headingText=" + $("#headingText").val() + "&centerText=" + $("#centerText").val(); $.ajax({ url: "indexpdf.php", data: str, ...

Leveraging Deferred in conjunction with AJAX

I am facing an issue with a series of JavaScript functions that make database calls using AJAX. I need these functions to finish executing and update variables before moving on to the final function. I have attempted to use jQuery $.when but it is not work ...

AngularJS: How service query data is perceived as an object and therefore cannot be utilized by Angular

When retrieving data from my PHP server page in the factory service, I encountered two different scenarios: If I call a function that returns an array and then use json_encode($data); at the end, Angular throws a resource misconfiguration error due to ...

Determining the element type that was clicked using Angular

Is there a way in Angular to determine the type of element that was clicked? I have successfully implemented this functionality using jQuery, but I'm unsure how to achieve the same outcome in an Angular project. // Click action $(".contactlist").on(" ...

Has anyone experienced challenges with _POST data getting blocked on a hosting server provided by Godaddy?

Utilizing a form processor known as JotForm, I have encountered an unusual issue. When attempting to print all POST data, I am faced with an empty array, specifically when the page is hosted on GoDaddy. Strangely, while hosting it locally on localhost, no ...

Issue with IE11: Flexbox with absolute positioning not sizing correctly, fills entire width instead of individual content

Here's a simple case to reproduce the issue: <div style="display: inline-block; position: relative; border: 1px solid black;"> short <div style="display: flex; position: absolute; border: 1px solid black; top: 100%; lef ...