Enhance a link using jQuery to allow it to expand and collapse

I am currently working on an MVC view that features a 3-column table showcasing a list of products. The first column, which contains the product names, is clickable and directs users to a specific product page. I am looking to implement functionality where, upon clicking the product name link, the product description for that item expands below it. At the end of the expanded description, there should be a link to the product page. Clicking the link again should collapse the description. Each product has its own field in the model where the description is stored.

Below is how the table is constructed and populated. Any advice or suggestions on how I can achieve the expand/collapse effect using jQuery would be greatly appreciated.

<table id="products">
    <thead>
        <tr>
            <th>Product Name</th>
            <th>Type</th>
            <th>Price</th>
        </tr>
    </thead>

    <tbody>
         foreach (product p in model.products)
         {
             <tr>
                 <td>
                     @p.name
                  </td>
                  <td>
                      @p.type
                   </td>              
                      <td>
                           @p.price
                        
                       </td>
                    </tr>
                }

         </tbody>
    </table>

Answer №1

To simplify the process, consider incorporating product IDs as well. Include the specific product ID as a data attribute and then leverage jQuery to extract and reuse it for targeting rows containing descriptions.

$('.productname').on('click', function() {
      var id= $(this).attr('data-id');
    $(this).toggleClass('active');
      $('.data' + id).slideToggle(500);
    });
.hide  {display: none; }


/* -- below is just to "pretty up" the snippet ------ */


table {
  width: 100%;
  background: #eee;
  border-collapse: collapse;
border: 1px solid #aaa;}
th { background: #cef; color: #4cf; text-transform: uppercase; font-size: 0.8em; padding: 3px;border: 1px solid #aaa;}
td { font-size: 1.1em; padding: 5px 10px; border: 1px solid #aaa; border-bottom: none; }
tr.collapsed td { padding: 0; border: none; }
.productname:hover, .active { background: #eff; }
.productdesc { padding: 5px 10px; background: #eff;  border-top: 1px solid #aaa; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="products">
        <thead>
            <tr>
                <th>Product Name</th>
                <th>Type</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
          
          <!-- 
               foreach (product p in model.products)
                {
-->
                    <tr class="productname" data-id="prodID00">
                      <!-- Change data-id="prodID00" to data-id="@p.productI‌D" -->
                      
                        <td>
                            @p.name
                        </td>
                        <td>
                            @p.type
                        </td>
                        <td>
                            @p.price
                        </td>
                    </tr>
                    <tr class="collapsed">
                      <td colspan="3">
                        
                        <div class="hide productdesc dataprodID00">
                        <!-- Change class="hide productdesc dataprodID00" to class="hide productdesc <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9b9e8b9ebf8fd18f8d909b8a9c8bb6">[email protected]</a>‌D" -->
                          
                        <p>@p.productDescription <a href="#">@p.productLink</a></p></div>
                        </td>
                      </tr>
          
          <!-- } -->
          
          
          <!-- below are just manual iterations of the row above -->
          
                    <tr class="productname" data-id="prodID01">
                        <td>
                            @p.name
                        </td>
                        <td>
                            @p.type
                        </td>
                        <td>
                            @p.price
                        </td>
                    </tr>
                    <tr class="collapsed">
                      <td colspan="3">
                        <div class="hide productdesc dataprodID01">
                        <p>product description and <a href="#">link</a></p></div>
                        </td>
                      </tr>
                    <tr class="productname" data-id="prodID02">
                        <td>
                            @p.name
                        </td>
                        <td>
                            @p.type
                        </td>
                        <td>
                            @p.price
                        </td>
                    </tr>
                    <tr class="collapsed">
                      <td colspan="3">
                        <div class="hide productdesc dataprodID02">
                        <p>product description and <a href="#">link</a></p></div>
                        </td>
                      </tr>
                    <tr class="productname" data-id="prodID03">
                        <td>
                            @p.name
                        </td>
                        <td>
                            @p.type
                        </td>
                        <td>
                            @p.price
                        </td>
                    </tr>
                    <tr class="collapsed">
                      <td colspan="3">
                        <div class="hide productdesc dataprodID03">
                        <p>product description and <a href="#">link</a></p></div>
                        </td>
                      </tr>
                    <tr class="productname" data-id="prodID04">
                        <td>
                            @p.name
                        </td>
                        <td>
                            @p.type
                        </td>
                        <td>
                            @p.price
                        </td>
                    </tr>
                    <tr class="collapsed">
                      <td colspan="3">
                        <div class="hide productdesc dataprodID04">
                        <p>product description and <a href="#">link</a></p></div>
                        </td>
                      </tr>
        </tbody>
    </table>

Note where the prodID is located in the rows.....

I removed the foreach function and brackets because it's invalid HTML. However, if they dynamically generate the HTML, it should work smoothly. The rows used are simply manual iterations rather than dynamic ones.

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

Creating a series of images in JavaScript using a for loop

Currently attempting to create an array of images, but with a large number of images I am looking into using a "for loop" for generation. Here is my current code snippet : var images = [ "/images/image0000.png", "/images/image0005.png", "/ima ...

Calculating the dimensions of a CSS element based on its content

Is there a way to achieve this using only CSS, without needing JavaScript? I am working on a project with a lot of relative and absolute positions, where elements must be centered dynamically without specifying static widths. While I have managed to minimi ...

encountering difficulty with loading JavaScript code while customizing form fields in Symfony/Sonata Admin

I have been attempting to personalize a field in a form created with the Sonata Admin Bundle. I followed the solution provided in this article: Customize form field rendering. Apart from customizing the form field, I also aimed to implement an autocomple ...

Issues with ajax functionality

Utilizing Codeigniter When clicked ... .. insert some code.... $.ajax({ url: '<?php echo base _ url(); ?>locations/getmap', dataType: 'json', type: 'POST', data: location_data, success ...

Is it possible for JavaScript to interface with MySQL databases?

Is it possible to establish a connection between JavaScript and MySQL? If yes, what is the process? ...

Extracting precise information from HTML documents

Looking to extract specific data from an HTML file using C# and HtmlAgilityPack. Here is a snippet of the HTML: <p class="heading"><span>Greeting!</span> <p class='verse'>Hi!<br> // Hello!</p>& ...

Utilizing Django to recycle an HTML block for multiple for loops within the same template

I have three specific states for an object - 1. to start, 2. started, and 3. finished. Upon filtering the objects in view, I pass three variables to the template - tostart_objects, started_objects, and finished_objects. My current approach involves loop ...

Is there a way to calculate the number of days between two selected dates using the bootstrap date range picker?

I recently implemented the bootstrap daterange picker for selecting start and end dates, and it's been working perfectly. However, I now have a requirement to display the count of days selected. Here's my current code: $('input[name="datera ...

Automatically initiate a click event when the page is loaded

I'm having trouble getting a click event to trigger on my controller when the page loads. I really just want the checkboxes to be clicked automatically. <!DOCTYPE html> <html > <head> <link rel="stylesheet" type="text/css" ...

Title: How to Build a Dynamic Logo Carousel with React and CSS without External Dependencies

Currently, I am in the process of integrating a logo carousel into my React web application using CSS. My goal is to create a slider that loops infinitely, with the last logo seamlessly transitioning to the first logo and continuing this cycle indefinitely ...

Troubleshooting Issue: MVC 5 validation messages not displaying when using Ajax.BeginForm

Having recently delved into MVC 5, I've encountered some issues that have left me stumped despite my best efforts at troubleshooting. Specifically, my struggle lies in creating a validation mechanism for a user and password list to ensure that all fie ...

Applying a unique style to an element using its ID is effective, but using a class does

Incorporating twitter bootstrap tables has been a focus of mine lately, particularly when it comes to custom styling such as setting background colors for table elements. Here's what I've discovered: by assigning id="foo" to each <td> elem ...

Displaying object properties within another object obtained from an API request in a React component

Dealing with API data can be tricky, especially when there are nested objects involved. I've encountered an error message stating 'undefined is not an object (evaluating 'coin.description.en')', as the description property of the c ...

What is the best way to incorporate JQuery into html content retrieved through an ajax request?

In my jsp file, there is a div structured like this : <div id="response" class="response"></div> After triggering an ajax call to a servlet, the content of this div gets updated with the following elements : <div id="response" class="res ...

Is it considered secure to encase a function within jQuery's removeClass()?

I'm currently developing a unique slider that includes a dynamic video element. With each slide transition, a new video is added to the DOM while the previous one is removed. To achieve this effect, I am utilizing CSS transitions along with a specific ...

Populate a dropdown list with array elements using Javascript in ReactJS

I am encountering an issue while trying to populate a dropdown with data from the 'options' array. The error message states that it cannot read property appendChild of null. Using 'document.getElementByClassName' instead of document.ge ...

Display the table once the radio button has been selected

Before we proceed, please take a look at the following two images: image 1 image 2 I have over 20 fields similar to 'Image 1'. If "Yes" is selected, then a table like in 'Image 2' should be displayed. This means I have 20 Yes/No fields ...

Run JavaScript code whenever the table is modified

I have a dynamic table that loads data asynchronously, and I am looking for a way to trigger a function every time the content of the table changes - whether it's new data being added or modifications to existing data. Is there a method to achieve th ...

Organize results from MySql using php

Trying to retrieve table values from a MySQL database sorted has proven to be a challenge for me. While I am able to connect and update the table successfully, I struggle with displaying the messages in the HTML chat history sorted by time. Is there a mo ...

Grouping object properties in a new array using Java Script

I'm currently learning Java script and attempting to merge an Array of objects based on certain properties of those objects. For instance, I have the following array which consists of objects with properties a, b, c, pet, and age. I aim to create a n ...