Tips for displaying a table with a button click

I am struggling to figure out how to embed a table inside a button in order to display the table when the button is clicked and hide it when clicked again. Below is the code I have been working with:

function toggleTable(){    
  document.getElementById("displaytable").style.display = (document.getElementById("displaytable").style.display == "none") ? "block" : "none";  
}
<input type="button" value="Show/Hide Table" onclick='toggleTable();'>
<div id="displaytable" style="display: none">
  <table id="displaytable" style="width: 100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">Header 1</td>
      <td class="lbl">Header 2</td>
      <td class="lbl">Header 3</td>
    </tr>
    <tr>
      <td align="center">Cell 1</td>
      <td align="center">Cell 2</td>
      <td align="center">Cell 3</td>
    </tr>
    <tr>
      <td align="center">Cell 4</td>
      <td align="center">Cell 5</td>
      <td align="center">Cell 6</td>
    </tr>
  </table> 
</div>

Answer №1

To enhance the functionality of your code, consider modifying the ID assigned to your input element. Once this is updated, you can simplify your function as shown below:

function toggleDisplay()
{
    if (document.getElementById("displaytable").style.display === "none")
        document.getElementById("displaytable").style.display = "block";
    else
        document.getElementById("displaytable").style.display = "none";
}

Answer №2

If you're looking to expand your repertoire of solutions, consider utilizing the classList web API.

All you need to do is define a class, for instance:

hide{
display:none;
}

Then, simply toggle it using the toggle method within element.classList like so:

  tableelement.classList.toggle('hidden')

You can check out a live example here.

var click = document.getElementById('clickme');
click.addEventListener('click', myfunction);

function myfunction() {
  var tablewrap = document.getElementById('displaytable');
  tablewrap.classList.toggle('hidden')
};
.hidden {
  display: none;
}

.placeholder {
  font-size: 12px;
}
<div id="displaytable" class="placeholder">
  <table id="displaytable2" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>
<div>
  <input type="button" id="clickme" value="Show/Hide" />
</div>

To delve deeper into this topic, read more about it on the classList web API documentation.

Answer №3

This is a slight revision of your code using Vanilla JavaScript only. There are some minor differences in the HTML structure with new IDs added.

<input id="toggleVisibilityButton" type="button" value="Button1"/>
<table  id="displaytable" style="display:none" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
            <td class="lbl">column1</td>
            <td class="lbl">column2</td>
            <td class="lbl">column3</td>
            </tr>
    <tr>
            <td align="center">1</td>
            <td align="center">2</td>
             <td align="center">33</td>
            </tr>
            <tr>
            <td align="center">4</td>
            <td align="center">5</td>
           <td align="center">6</td>
            </tr>
</table> 

I have kept the JS code simple, assuming you are a beginner and do not require a more sophisticated solution:

document.getElementById("toggleVisibilityButton").addEventListener("click", function(button) {    
   if (document.getElementById("displaytable").style.display === "none") {
       document.getElementById("displaytable").style.display = "block";
   } else {
       document.getElementById("displaytable").style.display = "none";
   }
});

You can test it here: JS fiddle link

NOTE:

I made changes to how you bind your actions to elements. You were trying to do it directly from HTML to a function without storing as a variable, which is not considered the best practice.

Instead, I followed an approach known as: Unobtrusive JavaScript

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

What could be causing my HTML form to only accept one response at a time?

While conducting my study, I required a Likert scale and came across a well-designed one at https://codepen.io/Buttonpresser/pen/poXVod However, I encountered an issue where selecting an answer for one question would deselect the answer for a different qu ...

Placeholder for empty values in Angular UI mask

Currently, I have implemented the angular ui mask directive for a date field. However, it is inserting underscores as a placeholder. Is there a way to display nothing in the placeholder instead? ...

Should all pages in React be rendered on the server side?

Currently, I rely on Next.js for implementing server-side rendering on my React website. At the moment, I have implemented server-side rendering across almost all pages of the site, including profile information and other content that requires a login to ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

Order JSON Array Using LoDash Library

Recently I encountered a JSON array with the following structure: var json = [ { key: 'firstName', value: 'Bill' }, { key: 'lastName', value: 'Mans' }, { key: 'phone', value: '123.456.7890&apo ...

Switching JSON data when clicked in Angular 2

Looking for a way to dynamically switch between different data sets in JSON upon user interaction with UI buttons. I am utilizing Angular 2 framework for this task. The HTML structure is as follows: <button type="button" (click)="changeOdds('odds ...

Navigating from Page 1 to Page 2 and then returning to Page 1 using the browser's back button causes Page 1 to malfunction in NextJS version 13

I am currently using next version 13.4.5 and implementing routing with typescript through /app. On my first page, I have a <Link> (next/link) element that takes me to Page 2. However, when I use the browser back button to return to page 1, the layou ...

Extracting information from an HTML table with Jsoup

Currently, I am attempting to utilize jsoup in order to parse an HTML table. As a newcomer to jsoup, I have taken the time to review some tutorials on how it operates. My objective is to retrieve values from each column within this specific website's ...

What is the process for assigning an element to a specific URL ID?

Imagine having an array of objects structured like this: [{ details: {id: 7}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: 8}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: ...

Embracing Blackberry WebWorks for Enhanced HTML5 Support

Can someone assist me with this question? I am wondering if my Blackberry Bold 9700 (5.0.0.469) is capable of supporting HTML5 for audio streams. Thank you in advance. ...

Bypassing the "Your connection is not private" error in NodeJS + Express with fetch() using Javascript

Presently, I have a setup with a NodeJS + ExpressJS client-side server that communicates with the back-end server via API calls. However, every time I make a call, I need to manually navigate to the URL of the API back-end server and click on Advanced -> ...

Learn the method for switching between exclusive visibility using Bootstrap class toggles

I've set up a jQuery function that toggles the visibility of different divs when clicking on folder icons: $(document).ready(function() { $("#techfolder").click(function(){ $("#txt").toggleClass("d-none"); }); $("#persfolder").click(functio ...

Registering a function for chart.js plugins that manipulates external data

Is there a way to pass external data to the chart.plugins.register function? I'm struggling because I can't access the necessary context: Chart.plugins.register( { beforeDraw: function (chart) { //implementation } }); I attempted using ...

What is the technique used by express.js to handle ReferenceError?

// Here is a sample code snippet app.get("/test", (req, res) => { return res.status(200).send(SOME_UNDEFINED_VAR); }); If a ReferenceError occurs, express.js will automatically send a 500 error response. express.js logs the ReferenceError to std ...

How to Send a JavaScript Array to a JSP Endpoint

I'm in the process of creating a web application that interacts with another website through a JS API. I would like to incorporate an array of JSON objects obtained from this API into my Java Application. Is there any way to submit this array, perhap ...

Generating numerous circular elements for each item in the dataset using D3

My dataset consists of various years and corresponding numerical values for each year as shown below: "data":[ ["1951","306","27","159","34","82","4"], ["1956","426","41","203","47","119","16"], ["1959","562","67"," ...

Converting Angular object into an array: A step-by-step guide

In Angular, I have retrieved an object that contains the following information: quiz.js:129 m {$promise: Promise, $resolved: false} 439: "https://mysite.no/sites/default/files/styles/quiz_large/public/fields/question-image/istock_000059790188_large.jpg ...

Leverage Angular to highlight updated items within a list

My goal is to synchronize data, so I have a data object that holds the current state. Whenever this state changes, I want to mark the object with an attribute for filtering purposes during syncing. Here is the structure of the object: data = { type1: [ ...

Removing an object from an array if it does not exist in another array: A step-by-step

Looking to remove an object from an array if it's not present in another array. After doing some research, I came across a similar question on this link, but with a different array source. Below is the example from the link: var check = [1, 2, 3]; ...

Tips on Calculating the Number of Object Properties and Presenting Each Value Individually on a Dynamic Button with Click Event Attached

When it comes to displaying dynamic data with markers on a map, everything works fine up until this point. However, I've encountered some issues that I'm currently stuck on and not sure how to proceed. Dynamic data: { "page": 2, "data" ...