Enhance your table with jQuery for expanding and collapsing views with just a

Interactive Table Display

I am looking to create a table that shows more rows when the "View More" button is clicked. Once all rows are shown, the button text should change to "View Less" and clicking it will hide the extra rows. The functionality should be able to repeat itself.

        $('table tr:lt(4)').addClass('active');
        var rowCount = $('table tr').length;
        $('a.load_more').on('click', function(e) {
            e.preventDefault();  
            var $rows = $('table tr');
            var lastActiveIndex = $rows.filter('.active:last').index();
            $rows.filter(':lt(' + (lastActiveIndex + rowCount) + ')').addClass('active');
            if ($rows.filter(':hidden').length === 0) {
                $(this).html('view less').on('click', function () {
                    $rows.filter(':lt(' + (lastActiveIndex + rowCount) + ')').removeClass('active');
                    $('table tr:lt(4)').addClass('active');
                });
            }
             
        });

**CSS**
table tr { display: none; }
table tr.active { display: table-row; }

HTML Example Here's an example of what the HTML table structure could look like:

<table>
        <thead>
            <th>head 1</th>
            <th>head 2</th>
            <th>head 3</th>
            <th>head 4</th>
        </thead>
            <tbody>
                <tr>
                    <td>content</td>
                    <td>content</td>
                    <td>content</td>
                    <td>content</td>
                </tr>
                ...
                <tr>
                    <td>last row</td>
                    <td>last row</td>
                    <td>last row</td>
                    <td>last row</td>
                </tr>
            </tbody>
    </table>
    <a href="#" class="load_more">View More</a>

Answer №1

Check out this alternative approach that utilizes a toggle function instead

var initialCount = 3; // starting count = 3

$('#list li:lt(' + initialCount + ')').addClass('highlight');
var itemCount = $('#list li').length;

var isHidden = true;
var $list = $('#list');

$('button.toggle-button').on('click', function(e) {
  e.preventDefault();
  if (isHidden) {
    // first click, show hidden items
    $list.find('li:lt(' + itemCount + ')').hide();
    $list.find('li:lt(' + itemCount + ')').show();
    $(this).html('Show Less') //update text
  } else {
    $list.find('li:lt(' + itemCount + ')').hide();
    $list.find('li:lt(' + (initialCount - 1) + ')').show();
    $(this).html('Show More') //update text
  }
  isHidden = !isHidden;
});
#list li { display: none; }
#list li.highlight { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="list">
 <li>Item 1</li>
 <li>Item 2</li>
 <li>Item 3</li>
 <li>Item 4</li>
 <li>Item 5</li>
 <li>Item 6</li>
 <li>Item 7</li>
 <li>Last item</li>
</ul>
<button class="toggle-button">Show More</button>

Answer №2

To simplify, remove the active class from all table rows when the number of hidden rows is 0 and only add the active class to the first 4 rows. Otherwise, add the active class to the other rows as well.

Demo Code :

$('table tr:lt(4)').addClass('active');
var rowCount = $('table tr').length;
$('a.load_more').on('click', function(e) {
  e.preventDefault();
  var $rows = $('table tr');
  var lastActiveIndex = $rows.filter('.active:last').index();
  if ($rows.filter(':hidden').length === 0) {
    $rows.removeClass('active') //remove all active
    $(this).html('View More') //change html
    $('table tr:lt(4)').addClass('active'); //add class
  } else {
    $(this).html('view less')
    $rows.filter(':lt(' + (lastActiveIndex + rowCount) + ')').addClass('active');
  }
});
table tr {
  display: none;
}

table tr.active {
  display: table-row;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <th>head 1</th>
    <th>head 2</th>
    <th>head 3</th>
    <th>head 4</th>
  </thead>
  <tbody>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>last row</td>
      <td>last row</td>
      <td>last row</td>
      <td>last row</td>
    </tr>
  </tbody>
</table>
<a href="#" class="load_more">View More</a>

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

Convert the entirety of this function into jQuery

Can someone please help me convert this code to jQuery? I have a section of jQuery code, but I'm struggling with writing the rest! function showUser(str) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Guide to sending checkbox data using jQuery AJAX

I am facing an issue with submitting the form below: <form action="/someurl" method="post"> <input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5"> <input type="checkbox" class="mychoice" name="name" value="appl ...

Cannot Get jQuery .flip() to Work Automatically Every 2 Seconds

There are 3 words that I want to rotate on their x-axis every 2 seconds (repeating). Using jQuery: $(function () { count = 0; wordsArray = ["Innovation", "Creativity", "Success"]; setInterval(function () { count++; $("#words").text(wordsArray[co ...

Bootstrap dropdown malfunction

I am having trouble with my dropdown menu. The browser is cutting off the blue box in the dropdown area. I'm not sure if I need to add some CSS or make changes to the Bootstrap code to fix this issue. I haven't made any unusual modifications, jus ...

Is it possible to create a looped GLTF animation in three.js using random time intervals?

I am currently exploring the world of game development with Three.js and have a specific query regarding animating a GLTF model. Is it possible to animate the model at random intervals instead of in a continuous loop? In the game I am creating, players wil ...

Unavailability of dates in Json ajax DatePicker

After retrieving database records of dates and converting them into a JSON Object, I am attempting to pass the JSON to javascript. The goal is to make the DatePicker UI dynamic by marking the dates in the JSON as unavailable on the calendar. Unfortunately ...

All images must be arranged to fit seamlessly side by side regardless of the screen size

I'm currently experimenting with creating a website dedicated to my favorite TV shows. Upon entering the site, you are greeted with the main page that includes 7 images. Each image is linked to a specific webpage providing information about the corre ...

Tips for retrieving JSON data from an AJAX call and displaying it pre-filled in an input field

Here is the code snippet I used to receive a response in JSON format, but when I try to display the response using alert(response.Subject);, it shows as "undefined". HTML: <input type="text" id="subject" value='Subject'> Javascript: $.a ...

Transform text to lowercase and eliminate whitespace using JavaScript

I am a newcomer to the world of JavaScript and currently focused on building Discord bots. I have successfully coded a bot that responds to messages, but I'm facing issues when the input is in capital letters or contains spaces. The bot fails to res ...

Is it feasible for draggable divs to create a trail of lines as they are dragged?

Looking to create an interactive online coach tactic board where you can easily rearrange player positions and demonstrate specific tactics by dragging divs representing players. Utilizing Touch Punch for smooth dragging functionality on PCs, tablets, and ...

Show a FlatList horizontally within a schedule-themed scroll view element

Below is an illustration of the desired component. It features a schedule-like screen with a vertical scroll view for transitioning between time stamps and a FlatList for horizontal scrolling through items. Picture this as a weekly timetable for a gym, dis ...

I am able to access the JSON file from the URL without any issues, but for some reason, I am unable to fetch it using $

(function(){ $(document).ready(function(){ $.getJSON('http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=AAPL&callback=?', function(){console.log("function was run");}); }); }()) I recently delved into working with APIs. Ho ...

What is the best configuration to use for successful MapReduce queries in Riak?

While working on a nodejs application with riak / riak-js, I encountered the following issue: Executing this request db.mapreduce .add('logs') .run(); successfully retrieves all 155.000 items stored in the bucket logs along with their IDs ...

Navigating the ins and outs of Bootstrap 4 grids

I am trying to create a layout with two columns, each using the class col-md-6. In both columns, there are six images. However, I want to have only one image displayed in the left column if the right column is empty. How can I achieve this? The current se ...

Node JS Promise does not provide a value as a return

Struggling with getting a value back from the code snippet below, even though it console logs out without any issues. Any suggestions on how to assign a value to X? var dbSize = dbo.collection('Items').count() var x = 0 x = dbS ...

Creating a slider directly under the header in an Ionic 3 application without any gaps

I need help with positioning a slider below the header within the ion-content. The issue is that I am experiencing unwanted white space on the top, left, and right sides, as depicted in the image. https://i.sstatic.net/HH1c6.jpg This is my HTML code for ...

What is the best way to add an element while preserving its original placement?

I need a solution to duplicate the code of an element and transfer it to another element without removing it from its original position. Currently, I have a JavaScript function that allows you to move a picture to a box when it's clicked. However, th ...

Establish the lowest possible height for Angular Material Expansion Panel Content

Is there a way to specify a minimum height for the content of an Angular Material expansion panel when it is open? I have searched for examples on setting the expandedHeight and collapsedHeight for the header, but not for the content itself. The Angular Do ...

Can a single global variable be shared between a JavaScript file and a TypeScript file within an Angular project?

In my Angular 5 project, I am implementing a javascript library. If I create a global variable in my .js file, how can I access that variable from my .ts file? ...

Utilizing Node-Red: Linking an External CSS File with HTML Elements

If there are any resources on this particular topic available on the Node-Red website, please share them with me. My current project involves building a static website using HTML, JavaScript, and CSS with Node-Red. I am utilizing HTTP GET nodes to call my ...