Click the 'expand' button for additional details on every row in the table

I am facing a challenge with my HTML table where I have a lot of information to add for each row. However, displaying everything at once makes the page look cluttered. Therefore, I am looking to add a "view more" button in another column for each row.

Despite trying to write JavaScript code to achieve this, it is not working as intended. My requirements are:

  1. The row should remain invisible until I click the "view more" button (I attempted wrapping the tags inside a div, but it resulted in placing the row outside the table).

  2. I need the code to apply to all rows so that I don't have to create separate codes for each one.

  3. When viewing extended information for a row, I want other extended information to remain hidden.

  4. If possible, I would like a simple animation to show the extended content.

Below is the snippet of my HTML code:

<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Action</th>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td><a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;" class="btn bN-btn-base bN-btn-small">View More</a></td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="example" class="more">
                <p>John Doe is a man</p>
                <p style="text-align:right;"><a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;">Hide this content.</a></p>
            </div>
        </td>
    </tr>
    <tr>
        <td>Jane</td>
        <td>Doe</td>
        <td><a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;" class="btn bN-btn-base bN-btn-small">View More</a></td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="example" class="more">
                <p>Jane Doe is a woman</p>
                <p style="text-align:right;"><a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;">Hide this content.</a></p>
            </div>
        </td>
    </tr>
</table>

This is how the CSS looks like:

<style type="text/css">
   .more {
      display: none;
   }
   a.showLink, a.hideLink {
      text-decoration: none;
      color: #36f;
      padding-left: 8px;
      background: transparent url(down.gif) no-repeat left; 
   }
   a.hideLink {
      background: transparent url(up.gif) no-repeat left;
   }
   a.showLink:hover, a.hideLink:hover {
      border-bottom: 1px dotted #36f; 
   }
</style>

Finally, here is the JavaScript portion:

<script language="javascript" type="text/javascript">
function showHide(shID) {
   if (document.getElementById(shID)) {
      if (document.getElementById(shID+'-show').style.display != 'none') {
         document.getElementById(shID+'-show').style.display = 'none';
         document.getElementById(shID).style.display = 'block';
      }
      else {
         document.getElementById(shID+'-show').style.display = 'inline';
         document.getElementById(shID).style.display = 'none';
      }
   }
}
</script>

Answer №1

Assuming you are open to using jQuery since you've tagged it, here is a sample fix with jQuery:

UPDATE: The HTML has been modified, causing the second row to fail due to the ID selector

Markup Language (HTML)

<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Action</th>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td><a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;" class="btn bN-btn-base bN-btn-small">View More</a></td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="example" class="more">
                <p>John Doe is a man</p>
                <p style="text-align:right;"><a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;">Hide this content.</a></p>
            </div>
        </td>
    </tr>
    <tr>
        <td>Jane</td>
        <td>Doe</td>
        <td><a href="#" id="example-show" class="showLink" onclick="showHide('exampleFemale');return false;" class="btn bN-btn-base bN-btn-small">View More</a></td><!-- Note the change in the showHide() function -->
    </tr>
    <tr>
        <td colspan="3">
        <div id="exampleFemale" class="more"><!-- Note the change in the ID -->
                <p>Jane Doe is a woman</p>
                <p style="text-align:right;"><a href="#" id="example-hide" class="hideLink" onclick="showHide('exampleFemale');return false;">Hide this content.</a></p><!-- Note the change in the showHide() function -->
            </div>
        </td>
    </tr>
</table>

JavaScript

function showHide(shID) {
    if ($('#' + shID)) {
      if ($('#' + shID+'-show').css('display') != 'none') {
       $('#' + shID+'-show').css({'display':'none'});
       $('#' + shID).css({'display':'block'});
      }
   }
   else {
       $('#' + shID+'-show').css({'display':'inline'});
       $('#' + shID).css({'display':'none'});
   }
}

Notice the amendments in JavaScript->jQuery where

document.getElementById(shID+'-show')
used to be and now it's $('#' + shID+'-show'), and .style.display = 'none'; changed to .css({'display':'none'});

Remember to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Trust this explanation helps!

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 is the process of embedding a string with pug code into a pug file?

How can I interpolate a string with pug formatted code in a pug file? Here is what I have tried: - var text = "i.home.icon" div= text div !{text} div #{text} div ${${text}} div {{text}} div {text} div \#{text} div \{text} div ${text} div # ...

Extract data from a JSON file and refine an array

Currently, I am working with reactjs and have an array stored in a json file. My current task involves filtering this array using the selectYear function. However, when attempting to filter the data using date.filter, I encounter the following error: An ...

Ways to guarantee that a function runs prior to a console.log in Mongoose

I've created a function called findUser that I'm working on implementing using sails, MongoDb, and mongoose. Here's what the function looks like: findUser(userId); function findUser(user_id){ User.findOne({ _id: user_id ...

What is the best way to position an image next to an input element?

How can I position submit.png next to the input element in my code? <div class="input-box" style="height: 40px; width: 500px;"> <img src="img/delete.png" width="25px" height="25px;" style="position: absolute; right: 0;"> ...

Error encountered while trying to load component: template or render function is not defined

I have set up a basic vue.js configuration using browserify and vueify. Following advice from previous tutorials, I included aliasify as a dependency to utilize the template engine. Below is my package.json file: { "name": "simple-vueify-setup", "ve ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

The compatibility issue between jQuery Tabs and Sliding effect

Hey there, I'm currently working on a website that requires a vertical tab system. I also have an arrow image that shows which tab or thumbnail the user has selected, and it should smoothly slide between the two thumbnails. You can check out the pro ...

Exploring the power of AngularJS with JavaScript and utilizing the $scope

After spending the entire day trying to solve this issue, it seems like I might be missing something simple. Here's the problem at hand: I have a well-structured Nodejs/AngularJS application that utilizes Jade for templating. The server performs certa ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Vue component not receiving the updated prop value from parent component

I am encountering a problem with my parent-child component setup. The issue arises when I pass a validation field as a prop from the parent to the child, but it doesn't update upon the first click of the submit button in the child component. To explai ...

Using Fetch API in NextJS requires pressing the Enter key twice for it to work properly

The functionality of this component should display JSON data in the console log after entering input into the search bar and hitting the enter key. However, there is a lag where the data doesn't show until the enter key is pressed a second time. Addit ...

What steps do I need to follow to create a 3D shooting game using HTML5 Canvas?

I'm eager to create a 3D shooter game with HTML5 Canvas, focusing solely on shooting mechanics without any movement. Can anyone provide guidance on how to accomplish this? I've looked for tutorials online, but haven't come across any that m ...

Exploring the jQuery syntax within Twitter Bootstrap JS files

Questioning the syntax used in Twitter Bootstrap's JS files. Take for example this snippet from bootstrap-dropdown.js: !function ($) { /* ... */ /* Querying the Standard Dropdown Elements -- Inquiry Code * ================================= ...

Tips for overlaying a webpage with several Angular components using an element for disabling user interactions

I currently have an asp.net core Angular SPA that is structured with a header menu and footer components always visible while the middle section serves as the main "page" - comprised of another angular component. What I am looking to achieve is ...

Retrieve the initial entry from a Container for every row in the Table

I'm facing an issue with a table I have on my website. Here is the structure: <table id="fieldContainer"> <tr><td><input id="input1"></td><td><input id="input2"></td></tr> <tr><td>< ...

JQuery: Issue with closing modal on certain popups

I have configured a popup that is associated with 6 different products. While it functions correctly for the first product, it does not seem to work properly for the rest. <script> //var modal = document.getElementById("m ...

Receive information from the server and display it on the front-end

Hello! I'm currently in the process of developing a video uploader for my website. So far, I've successfully been able to upload videos from the front-end (built with React.js) to the back-end public folder (using Node.js) through the POST method ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Utilizing strings as data in Google charts with jQuery

When working with google charts, the code for generating a chart often looks something like this: var data = new google.visualization.DataTable(); data.addColumn('string', 'Topping'); data.addColumn('number', 'Slices&apo ...