When the next button is clicked, the button content disappears

I am struggling with a problem involving two buttons that store tables. The issue is, I want the table to disappear when the second button is clicked and show the contents of the second button immediately after clicking it once, rather than having to click it twice. I'm not sure how to achieve this.

function myFunction2() {
  var x = document.getElementById("displaytable");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<input type="button" id="Button1" value="Button1" onClick="myFunction2()" />
<div id="displaytable" style="display:none">
  <table id="displaytable" 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>

<input type="button" id="Button2" value="Button1" onClick="myFunction2()" />
<div id="displaytable" style="display:none">
  <table id="displaytable" 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">36</td>
      <td align="center">45</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>

Answer №1

To implement the required changes, you will need to follow these updates:

  • It is important to avoid using the same id for different elements, especially between buttons and divs. I suggest renaming them accordingly, for example as displaytable1, 2, and so on.

  • This code is designed to handle multiple buttons and corresponding tables without the need for separate functions for each one. By utilizing a loop, you can easily open the selected table while closing all others. This line of code achieves this functionality:

for(i=1;i<=2;++i), where '2' represents the maximum table id index (e.g., displaytable2).

  • The function takes an integer parameter based on the button or table's serial id, such as 1 for the first one and 2 for the second as demonstrated in the provided code snippet.
  • For better alignment and user experience, organize your buttons separately from the tables so that clicking a button does not disrupt their position relative to the tables.

function myFunction2(index) {
  var x = document.getElementById("displaytable"+index);
  for(i=1;i<=3;++i) //Considering we have 3 tables
  {
    if(index==i){
      x.style.display = "block";
    }
    else{
      document.getElementById("displaytable"+i).style.display = "none";
    }
  }

}
<input type="button" id="Button1" value="Button1" onClick="myFunction2('1')" />
<input type="button" id="Button2" value="Button2" onClick="myFunction2('2')" />
<input type="button" id="Button3" value="Button3" onClick="myFunction2('3')" />
<div id="displaytable1" style="display:none">

  <table 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 id="displaytable2" style="display:none">
  <table width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column2</td>
      <td class="lbl">column4</td>
      <td class="lbl">column5</td>
    </tr>
    <tr>
      <td align="center">36</td>
      <td align="center">45</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 id="displaytable3" style="display:none">
  <table width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column11</td>
      <td class="lbl">column23</td>
      <td class="lbl">column2</td>
    </tr>
    <tr>
      <td align="center">3</td>
      <td align="center">45</td>
      <td align="center">3</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">00</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>

Answer №2

You have improperly used the same id multiple times, which is not recommended. It is best practice to use classes or unique ids instead. Additionally, using the same id multiple times can lead to issues when working with JavaScript and is not considered standard coding.

JS:

function myFunction1() {
    var x = document.getElementById("displaytable1");
    var y = document.getElementById("displaytable2");
    y.style.display = "none";

    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

function myFunction2() {
    var x = document.getElementById("displaytable2");
    var y = document.getElementById("displaytable1");
    y.style.display = "none";
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

HTML:

<input type="button" id="Button1" value="Button1" onClick="myFunction1()"/>
<div id="displaytable1" style="display:none">
    <table id="displaytable1_1" 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>

<input type="button" id="Button2" value="Button1" onClick="myFunction2()"/>
<div id="displaytable2" style="display:none">
    <table id="displaytable2_2" 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">36</td>
          <td align="center">45</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>

P.S: I made adjustments by changing the id from displaytable to displaytable1 for the first div element and from displaytable to displaytable2 for the second div containing the second table, ensuring each table has a unique id. Regards

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

Converting "require" to ES6 "import/export" syntax for Node modules

Looking to utilize the pokedex-promise for a pokemonapi, however, the documentation only provides examples on how to require it in vanilla JavaScript: npm install pokedex-promise-v2 --save var Pokedex = require('pokedex-promise-v2'); var P = new ...

Error: Unable to access the 'resource' property as it is undefined

I am currently working on a project that involves fetching the latest 4 results from Craigslist using a query. Although I have successfully retrieved all the relevant information, I seem to be encountering an issue with loading the URL of the image from th ...

The candy stripes on a loading bar zebra assist in creating a unique and

I'm in the process of creating my portfolio and I'd like to incorporate unique animated loading bars, such as vertical or horizontal candy stripes, to showcase my coding skills. Can anyone suggest a specific programming language or tool that woul ...

The Angular app.component.html is failing to display the newly added component

Having some trouble rendering my new component in the browser. I've set up a fresh project using the Angular CLI and created a component named list-employees. Upon running ng serve -o, the project compiles without errors, but the browser displays a b ...

Is it possible to bring in Node's path module by using the import statement like this: `import path from 'path'`?

My preference lies with using the import x from 'y' syntax, however, all that has been brought to my attention online is the usage of const path = require('path'). I am curious if there exists a method of importing the path module util ...

Could a javascript loop be created to continuously activate a button with each iteration?

I have just started learning javascript and I am in the process of creating a website where users can change the background by simply clicking on a button. It's working perfectly fine so far, but I want to add another feature where the background imag ...

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...

A comprehensive guide on iterating through an array in JavaScript

Currently, I am facing an issue while trying to iterate over an array of Objects in React that have been fetched from Django. The object is stored as an array, but when attempting to map it, I encounter a typeerror stating "cannot read property map of unde ...

What steps should I follow to install nodemon on my Windows 10 device?

Currently, I am utilizing the bash console on my Windows 10 system. My goal is to install nodemon using node.js, but when attempting to do so, I encounter this error message: sudo: npm: command not found It's puzzling because I should already have n ...

JavaScript/CSS memory matching game

Just starting out in the world of programming and attempting to create a memory game. I've designed 5 unique flags using CSS that I want to use in my game, but I'm feeling a bit stuck with where to go next. I understand that I need some function ...

What criteria should I use to determine if a post has been favorited by a user using Mongoose?

Creating a function for users to like posts has been my recent project. Each post is stored as an object in my MongoDB collection with a specific schema. { title: String, text: String } On the other hand, users have their own unique schema as well. ...

Elegant Border Separator

I'm attempting to achieve the design below (with a 1 pixel gap on each end): ...

Ensuring the bottom border of an element extends to the edge of the screen when utilizing a 960 grid in HTML/CSS

I am currently working on creating a website layout using the 960 grid system developed by Nathansmith. I am facing an issue in extending the bottom border of an element to reach till the end of the screen while keeping the element inside a container div. ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

Guide to building a React project with an outdated edition of Create React App

Currently, I'm following an older tutorial to learn React, and as a result, I need to set up a project using Create React App version 1.5.2. I successfully installed <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204352454 ...

Can you remind me of the specific CSS class used for Internet Explorer in Twitter Bootstrap?

Currently utilizing Twitter Bootstrap and curious if there is a specific CSS class to designate IE browsers within the BODY or HTML tags. Interested in writing CSS specifically for all IE browsers. Aware that Bootstrap offers some CSS classes for IE brows ...

Animating SVG elements using CSS

After learning how to use the <animate> attribute, I successfully created a captivating animation featuring an elastic line. However, I am now determined to transform this into CSS for better control: my goal is to activate the animation only upon ho ...

A chart using JavaScript that displays text values instead of a traditional website

I am a student with no background in programming, however, for my project I need to create a chart based on values from a txt file to display sensor data. I came across a chart that retrieves its values from a website, but I would like to modify it so it c ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...