Tips for inserting an HTML table into a div element using JQuery/JavaScript

I currently have a navigation bar with only two items. While I may potentially add more items in the future, for now I am content with just these two. Upon opening the page, my goal is to display the content of the first item in the navigation bar. Each item corresponds to a separate table, and on load, the first table should be visible on the page. When a user clicks on a different link, I want the corresponding table to be displayed. I am uncertain about the best approach or solution to tackle this issue. Below is the HTML code I am working with:

<div class="container">
   <section class="mainBox">
        <h3>Home Page</h3>
        <nav class="xNavigation">
            <a href="#" id="tab1" onClick="openTab('tab1')">Info 1</a> |
            <a href="#" id="tab2" onClick="openTab('tab2')">Info 2</a> |
        </nav>
        <div id="dataContainer">
           //Here I want to load the tables
        </div>
    </section>
</div>

I have already created tables on the page as follows:

<table class="tab1Class" id="tab1Tbl">
    <caption>Info 1</caption>
    <tr>
        <th>Last Name</th>
        <th>First Name</th>
        <th>DOB</th>
    </tr>
    <tr>
        <td><input type="text" name="lname" id="lname" value="" size="20" maxlength="30" readonly /></td>
        <td><input type="text" name="fname" id="fname" value="" size="20" maxlength="30" readonly /></td>
        <td><input type="text" name="dob" id="dob" value="" size="10" maxlength="10" readonly /></td>
    </tr>
</table>

<table class="tab2Class" id="tab2Tbl">
    <caption>Info 2</caption>
    <tr>
        <th>Last Name</th>
        <th>First Name</th>
        <th>DOB</th>
    </tr>
    <tr>
        <td><input type="text" name="lname2" id="lname2" value="" size="20" maxlength="30" readonly /></td>
        <td><input type="text" name="fname2" id="fname2" value="" size="20" maxlength="30" readonly /></td>
        <td><input type="text" name="dob2" id="dob2" value="" size="10" maxlength="10" readonly /></td>
    </tr>
</table>

My aim is to load the first table upon page load, and then switch to the second table based on the user's selection. I am unsure whether the table should be removed from the container or simply hidden.

Below is an approach I attempted, but it did not yield the desired results:

function openTab(tblID){
        $('.xNavigation a').each(function(i){
            if(this.id == tblID){
                $('#'+tblID).show();
            }else{
              $(this.id).hide();
            }
        });
    }

If anyone has insights on how to solve this problem, please share your knowledge.

Answer №1

Consider using a different approach by assigning a data-id attribute to tables instead of individual ids, then toggle based on that:

JS Fiddle Example

Streamline the JavaScript code:

$('.xNavigation a').on('click', function() {
  var id = $(this).prop('id');
  $('#dataContainer > table[data-id=' + id + ']').show();
  $('#dataContainer > table:not([data-id=' + id + '])').hide();
});

Initially place both tables in their correct positions but hide the ones you do not want visible like this:

CSS

#dataContainer > table:not([data-id="tab1"]) {
  display: none;
}

HTML

<div class="container">
  <section class="mainBox">
    <h3>Home Page</h3>
    <nav class="xNavigation">
      <a href="#" id="tab1">Info Group 1</a> |
      <a href="#" id="tab2">Info Group 2</a> |
    </nav>
    <div id="dataContainer">
      <table class="tab1Class" data-id="tab1">
        <caption>Table for Info Group 1</caption>
        <tr>
          <th>Last Name</th>
          <th>First Name</th>
          <th>Date of Birth</th>
        </tr>
        <tr>
          <td>
            <input type="text" name="lname" id="lname" value="" size="20" maxlength="30" readonly />
          </td>
          <td>
            <input type="text" name="fname" id="fname" value="" size="20" maxlength="30" readonly />
          </td>
          <td>
            <input type="text" name="dob" id="dob" value="" size="10" maxlength="10" readonly />
          </td>
        </tr>
      </table>

      <table class="tab2Class" data-id="tab2">
        <caption>Table for Info Group 2</caption>
        <tr>
          <th>Last Name</th>
          <th>First Name</th>
          <th>Date of Birth</th>
        </tr>
        <tr>
          <td>
            <input type="text" name="lname2" id="lname2" value="" size="20" maxlength="30" readonly />
          </td>
          <td>
            <input type="text" name="fname2" id="fname2" value="" size="20" maxlength="30" readonly />
          </td>
          <td>
            <input type="text" name="dob2" id="dob2" value="" size="10" maxlength="10" readonly />
          </td>
        </tr>
      </table>
    </div>
  </section>
</div>

Answer №2

  1. Place your tables within the designated div #dataContainer. There is no need to load them there, simply show/hide the ones you wish to display.

  2. Add the css class 'tabTable' to all tables, and give the first table an additional class named 'active'

  3. Each table already has a unique id, so ensure they each have one as it is essential.

  4. Utilize CSS to conceal all elements with the class tabTable

  5. Assign the class of tabLink and the attribute data-opens="[id-of-table]" to all links that will toggle between tabs. Replace [id-of-table] with the unique id of the corresponding table.

  6. Implement the JavaScript code provided below

  7. Here's a JSfiddle

JavaScript

$(document).ready(function () {
  $(document).on('click', '.xNavigation a.tabLink', function (evt) {
    evt.preventDefault();
    var opens = $(evt.target).data('opens');
    $('.tabTable').removeClass('active');
    var el = $('#' + opens).addClass('active');
  });
});

CSS

.tabTable { display: none }
.tabTable.active {display: table} /* Since we're using tables instead of divs */

HTML

<div class="container">
   <section class="mainBox">
      <h3>Home Page</h3>
      <nav class="xNavigation">
          <a href="#" class="tabLink" id="tab1" data-opens="tab1Tbl">Info 1</a> |
          <a href="#" class="tabLink" id="tab2" data-opens="tab2Tbl">Info 2</a> |
      </nav>

      <div id="dataContainer">
<table class="tabTable active" id="tab1Tbl">
    <caption>Info 1</caption>
    <tr>
        <th>Last Name</th>
        <th>First Name</th>
        <th>DOB</th>
    </tr>
    <tr>
        <td><input type="text" name="lname" id="lname" value="" size="20" maxlength="30" readonly /></td>
        <td><input type="text" name="fname" id="fname" value="" size="20" maxlength="30" readonly /></td>
        <td><input type="text" name="dob" id="dob" value="" size="10" maxlength="10" readonly /></td>
    </tr>
</table>

<table class="tabTable" id="tab2Tbl">
    <caption>Info 2</caption>
    <tr>
        <th>Last Name</th>
        <th>First Name</th>
        <th>DOB</th>
    </tr>
    <tr>
        <td><input type="text" name="lname2" id="lname2" value="" size="20" maxlength="30" readonly /></td>
        <td><input type="text" name="fname2" id="fname2" value="" size="20" maxlength="30" readonly /></td>
        <td><input type="text" name="dob2" id="dob2" value="" size="10" maxlength="10" readonly /></td>
    </tr>
</table>
      </div>
    </section>
</div>

Answer №3

1.) Hide both tables within a concealed section.
2.) Invoke openTab with the specific table identifier (tab1Tbl or tab2Tbl).

openTab(tabId):
1.) If there is a table in #dataContainer, relocate it to the hidden section.
2.) Retrieve the table with #tabId from the concealed area and transfer it to #dataContainer.

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

Incorporating local JSON data into HTML: A Step-by-Step

I'm completely new to javascript and the utilization of json. What I want to accomplish is quite straightforward, although I am encountering difficulties. My objective is to create a website consisting of two pages: one that showcases artists and ano ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

Viewing content on a mobile device and using the scrolltop

I am working on a website that needs to be mobile-friendly. With the release of iOS 7, I wanted to achieve a depth and blurry effect. I used an iframe with a CSS3 filter applied to it and made it scroll along with the page using jQuery. Everything looks go ...

Elements vanish when SHAKE effect is in use

I've been experimenting with this framework and I'm struggling to get the shaking effect to work properly. Whenever I hover over an element, other divs seem to disappear. I tried using different versions of JQuery and JQuery UI on JSFiddle, and i ...

Experiencing Chrome freezing issues due to a setInterval function in combination with React

Can anyone assist me with a countdown issue using React? I am trying to set the minutes and seconds by clicking on + and - buttons, then passing the seconds to a new variable called tottime. However, when the user clicks on Go!, the countdown should start ...

Design a food selection with only CSS and HTML

I am working with a menu structure that looks like this: <ul class"menu"> <li> <a>item1</a> <ul> <li><a>subitem1</a></li> <li><a>subitem2</a></li> &l ...

Image floating to the left and right sides within a group, with the text vertically aligned in the middle of a div of unspecified height

Can text be vertically aligned in the middle of a div with an unknown height when there is a floated image present? Specifically, for the first and third div group of 'groupsection2', the image will float to the left; and for the second and fourt ...

What could be causing the caller to not recognize the success of my AJAX action's return?

In my ASP.NET MVC project, I have an AJAX call in the script section of my View: $(".ckbx").change(function () { . . . $.ajax({ type: 'GET', url: '@Url.Action("GetUnitReportPairVals", "Home")', data: { unit: ...

How to vertically align text within a container in Bootstrap?

Lately, I've been facing a challenge in my attempts to vertically center text while also incorporating a full-width background image. The goal is for the centered text to maintain its position regardless of the height of the enclosing container. This ...

Host your own website online using your personal computer

So I have created a simple HTML page that I want to publish on the Internet using my PC. This is just for testing purposes, so I don't require a static IP address or high uptimes. First, I installed Tomcat Apache and placed my WAR file in the webapps ...

Aligning images and input fields vertically with relative measurements

I'm looking for a way to vertically position two images, one on the left and one on the right, so that they are centered between labels and input fields within a containing div. Is it achievable using only relative lengths? Check out this jsfiddle fo ...

The jQuery library fails to load on the webpage

I'm a beginner to jQuery, and I've put together a basic index.html file with a simple script. However, it seems like the jQuery library isn't loading properly because I'm seeing this error in my firebug console: TypeError: $ is not a ...

Can I exclusively utilize named exports in a NextJS project?

Heads up: This is not a repeat of the issue raised on The default export is not a React Component in page: "/" NextJS I'm specifically seeking help with named exports! I am aware that I could switch to using default exports. In my NextJS ap ...

continuously repeating css text animation

How do I create an animation loop that slides infinitely, repeating non-stop in full screen without breaking at 'hello5'? I want to display 3 rows of the same item from my items array. Not sure which CSS is causing the issue. The result I am loo ...

Is there a way to override the JSON.stringify method within the JSON class of a TypeScript project without using a custom call?

Dealing with a React Native and TypeScript app here. I keep encountering an error from Fabric every week: "JSON.stringify cannot serialize cyclic structures." The frustrating part is that the error seems to pop up randomly, without any specific scenario tr ...

Dragging and dropping an HTML canvas element causes its width and height to be reset to zero

I am currently developing a customizable dashboard that allows users to rearrange dashboard tiles (represented by div elements) and position them anywhere within the dashboard. HTML Structure The HTML structure is outlined in the snippet below: <div cl ...

Enhance your Bootstrap Progress Bar by incorporating the width value within the CSS using CoffeeScript or jQuery

I'm attempting to create a function where every time the button is clicked, the progress bar increases by an extra 12.5% out of the total 100%. (Therefore, eight clicks will complete the progress bar to 100%) Currently, it updates the text content bu ...

The accumulation of MVC 3 Ajax requests is becoming overwhelming

I'm currently working on the following code snippet: $('.defaultLink').click(function () { $.ajaxSetup({ cache: false }); cleardiv(); $('#mainContent').empty() $('#mainContent').load(this. ...

Disable automatic playback of HTML video

There is an HTML video with an image that loads initially and then disappears to play the video. I would like the image to always be visible until I click on it. Once clicked, the video should start playing. You can view the code on JSFiddle: http://jsf ...

Irritating Popup - (or perhaps a more elegant alternative)

My current challenge involves tracking the time a user spends with a specific window in focus. I aim to record this duration accurately and pause the timer when the user switches to another window, then resume it upon returning. Ultimately, I want to measu ...