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

Manipulating JSON Elements using JavaScript in HTML

My objective is to alternate the visibility between the "prev" and "ext" elements retrieved from the JSON File in the following manner: Here is the link to JS Fiddle The menu bar appears as follows: [ "prev_Person1" "Person1" "ext_Person1" ... "Person2" ...

Controlling the document object model of a third-party website within the Electron framework

I am completely new to electron. My main goal is to load a URL and then execute some Javascript that will make changes to the DOM. Currently, my approach involves creating a BrowserWindow that loads the URL, and I understand that I can utilize webContents ...

Instructions for integrating AJAX into a PHP script

I am looking to incorporate AJAX into my PHP file so that when I delete an item from a list, the data automatically reloads and the list is updated with the new information. I have created a list of all my data along with a delete button. Below is the PH ...

A guide on utilizing Puppeteer for capturing screenshots of web pages with embedded videos

Currently, I am using Puppeteer to access a website and capture a screenshot of a video. Unfortunately, the default Chromium browser that Puppeteer uses does not support certain video types. I have managed to get it working by launching Puppeteer with a l ...

Angular's method of one-way binding to an object

Seeking a method for one-way (not one time) binding between an attribute on a directive without utilizing attrs.$observe. Currently considering binding via &attr and invoking the variables in the template like {{attr()}}. app.controller('MainCtrl ...

HTML code for an admin login form

Looking for a way to create a login form without PHP in HTML for an administrator account, so the admin information remains secure and cannot be easily accessed from a database. Any suggestions or tips on how to achieve this? ...

Converting a unix timestamp to a Date in TypeScript - a comprehensive guide

To retrieve the unix timestamp of a Date in plain JavaScript and TypeScript, we can use this code snippet: let currentDate = new Date(); const unixTime = currentDate.valueOf(); Converting the unix timestamp back to a Date object in JavaScript is straight ...

Enhance your message inbox experience with jQuery/Javascript features inspired by Gmail, including the ability to select all messages with a checkbox and

It is truly satisfying to be here working on developing a private message inbox for my website, especially after successfully implementing a complete user signup/login and activation system. A few months ago, I never believed I had enough patience to grasp ...

Issue with AJAX POST request: PHP failing to establish session

I would like to pass the element's id to PHP and create a session for it. This snippet is from a PHP file: <?php $sql = "SELECT id FROM products"; $result = mysqli_query($con,$sql); while($row = mysqli_fetch_array($result)) { ?> <tr cl ...

The modal in Bootstrap V5 refuses to hide using JavaScript unless the window method is utilized

Currently in the process of developing a react application and utilizing standard bootstrap. The command to display a modal and switch to one is functioning properly; but, the command to hide the modal does not work unless I establish it as a property on t ...

Styling with CSS: Changing the Background Color of Text

Looking for a solution to apply line-height to text without affecting the background color? Check out the code snippet below and share your ideas if you have any. Thanks! .nb-semnox-impact-grid { display: block; font-size: 6 ...

Variety of perspectives on Magento products

Is there a way to configure Magento 1.7 to display view.phtml for bundled products and view.phtml for simple products, or the other way around? I am looking to customize the views for different product types - what is the best approach to achieve this? ...

Make sure the "Treat labels as text" option is set to true when creating a chart in a Google spreadsheet using a script

I am currently working on a script using Google Spreadsheet Apps Script interface and I need to set the marker for 'Treat labels as text' to true. Despite searching through App Script documentation, I couldn't find any specific mention of t ...

Understanding which page is being rendered through _app.js in React/Next.js is crucial for seamless navigation and

Currently, I am working on rendering my web navigation and footer on my _app.js file. My goal is to dynamically adjust the style of the navigation and footer based on the specific page being accessed. Initially, I considered placing the navigation and foot ...

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...

What is the best way to enable an image to be moved on top of another image?

Is there a way to allow users to drag around an image that is positioned on top of another image in an HTML file? I want the superimposed image to stay within the boundaries of the underlying image. Any suggestions on how this can be achieved? <html& ...

Limit selection choices in select element

Similar Question: Prevent select dropdown from opening in FireFox and Opera In my HTML file, I have a select tag that I want to use to open my own table when clicked. However, the window of the Select tag also opens, which is not desirable. Is there a ...

Is there a way to retrieve information from a different object?

Access the code on Plunker I am working with two data structures - ingredients and recipes [{ "id":"1", "name": "Cucumber" }, .. ] and [{ "id":"1", "name": "Salad1", "recipein":[1, 3, 5] }, { ... } ] My goal is to ...

What steps should I take to link form inputs from various child components to an array that is set in a parent component?

I'm in the process of linking form input from various child components (item-input-component) to an array itemList[] that is defined in a parent component (add-invoice-component). The goal is to gather three inputs (itemName, quantity, price), create ...

Error: The "res.json" method is not defined in CustomerComponent

FetchData(){ this.http.get("http://localhost:3000/Customers") .subscribe(data=>this.OnSuccess(data),data=>this.OnError(data)); } OnError(data:any){ console.debug(data.json()); } OnSuccess(data:any){ this.FetchData(); } SuccessGe ...