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

Is there a way for me to come back after all child http requests have finished within a parent http request?

I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player. Due to the structur ...

Utilizing Objects as Properties in Phaser.Scene in Phaser 3

I've just started working with Phaser using TypeScript and I'm facing an issue. I attempted to move my main objects out of the create and preload methods by loading them as Phaser.Scene class properties. However, after making this change, my game ...

Unable to append DOM element using the node.insertBefore() method

I am facing an issue with a sorted list of items displayed alphabetically. My intention was to insert a corresponding letter from the alphabetArr array after each <li> element, using an id from the DOMElementsArr array. However, I seem to be missing ...

ASP.NET repeater causing jQuery scrollTop to malfunction after first use

I am facing a peculiar issue where I need to scroll through repeater items in a RadWindow using arrow keys in an ASP.NET application. Below is the code snippet: function isScrolledIntoView(elem) { var docViewTop; var docViewBottom ...

Using setTimeout or setInterval for polling in JavaScript can cause the browser to freeze due to its asynchronous

In order to receive newly created data records, I have developed a polling script. My goal is to schedule the call to happen every N seconds. I experimented with both setTimeout() and setInterval() functions to run the polling task asynchronously. However ...

When creating a dynamic page number using JavaScript during a print event, the height of an A4 page is not taken into

While creating my A4 invoice using HTML, CSS, and JS, everything appears correctly in the print preview. However, I am encountering an issue where the page number is not aligned properly and extra empty pages are generated automatically. Below is a snippe ...

In Next.js, the elements inside the div created by glider-js are not properly loaded

I'm currently working on setting up a carousel in nextjs using the data retrieved from an API and utilizing glider-js for this purpose. However, I'm facing an issue where the div created by glinder-js does not include the elements that are render ...

Why is the error message "Invalid field name: '$conditionalHandlers' in 'collaborators..$conditionalHandlers'" popping up now?

Currently, in my Node/Express/Mongoose application (latest versions), I am working on a feature that involves "Projects" with a list of "collaborators" identified by the IDS of "Users". To simplify complex aggregations, I have decided to store these IDS as ...

The arrangement of elements varies based on the type of display

I'm still learning HTML and CSS, and I've noticed that the layout of my elements changes depending on the screen size. Everything looks good on my 24" monitor, but some elements overlap on my 15" laptop screen. What could be causing this issue, ...

Unable to render Google map on Vue CLI component

I am currently using the google map api to develop a basic application with vue.js. Interestingly, when I utilize a simple html and javascript setup with the api key, everything runs smoothly. However, once I transition the same process to vue, the map fai ...

When iteratively utilizing the setValue() function, an unintentional occurrence of an 'Uncaught error' is encountered

I encountered an issue while trying to update a spreadsheet upon submitting a form. The problem is that after pressing the submit button, the remaining commands are not being executed properly. As a result, I see an error message in the console saying "U ...

Why does the Google Tag Manager noscript tag show up as a string when using react-gtm-module?

Implementing Google Tag Manager Tags in a React/Next.js app hosted on Netlify, I used the react-gtm-module. While the gtm script tag in the head section works perfectly, the noscript tag in the body is displaying an iframe as a string: <body> < ...

Dealing with unsupported CSS properties in Next.js or implementing @supports directives in Chakra-UI

Currently, I am working on a React component that adjusts opacity values based on the support for the CSS backdrop-filter directive: background={(() => { const opacity = isBackdropFilterSupported() ? 0.75 : 0.98 return ( `linear-gradient( ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

The perplexity of ES6 Promises

Within an asynchronous function, I encountered the following code snippet: await application.save((err) => { console.log("hello"); if (err) { res.status(500).send({ message: "Error encountered" }); } }); conso ...

Only one JSON file is handled at a time, no duplicates are made

We start by utilizing the powerful D3 JavaScript library for initializing data documents, followed by creating a custom JavaScript script to handle data processing. An excerpt from the customized JavaScript script appears as follows: drawLegend(); ...

How can I handle a 404 error if an object is not found in a JSON file?

Below is my code snippet where I check for the correct req.path and display specific text. However, I now need to show a 404 not found error message. I attempted placing it inside the for loop condition with break;, but it's not quite working as expe ...

Delay the execution in selenium webdriver using Java until the login button is clicked manually

Can Selenium Webdriver be used to pause code execution with webdriver.wait until the user clicks the login button on a form? The form includes a Captcha that requires manual input, preventing automated clicking of the button by the script. Clicking the log ...

Unidentified googletagmanager detected in vendors segment

Recently, my ad blocker detected an unfamiliar Google Tag Manager request originating from a chunk provided by one of my vendors. Is it typical for tracking to be embedded in dependencies like this? And what type of information can be collected from my we ...

What is the best way to access the form button inside a div element?

Here is the code snippet for my form: <form accept-charset="utf-8" action="https:example.com" method="get" name="test"> <div class="classy"><input type="button" class="buttonE ...