What is the method to reveal concealed table rows in JavaScript?

I am working on a table with a unique functionality. The table has 5 rows, but only the first row is visible while the last 4 rows are hidden.

<table> 
  <tr> 
   <th>sr</th> 
   <th>Head</th>
  </tr> 
 <tr style="display:block;"> 
   <td>1</td> 
   <td>row 1</td> 
 </tr > 
<tr style="display:none;"> 
   <td>2</td> 
  <td>row 2</td> 
 </tr> 
<tr style="display:none;"> 
   <td>3</td> 
  <td>row 3</td> 
 </tr> 
 <tr style="display:none;"> 
   <td>4</td> 
  <td>row 4</td> 
 </tr> 
 <tr style="display:none;"> 
   <td>5</td> 
  <td>row 5</td> 
 </tr> 
 </table>
 <button id="add">Add row</button>
 <button>Remove row</button>

Here is what I have attempted using javascript:

$('#add').click(function() {
rows.show();
});

The desired functionality is that when the "Add row" button is clicked, the next hidden row should be displayed. Similarly, clicking on "Remove row" should hide the latest visible row.

Answer №1

To locate the initial occurrence of a hidden tr and final appearance of a visible tr, utilize the following method:

$(document).on('click','#add',function(){

  $('table tbody').find('tr:hidden:first').show();

});
$(document).on('click','#remove',function(){

  $('table tbody').find('tr:visible:last:not(:first-child)').hide();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> 
  <tr> 
   <th>sr</th> 
   <th>Head</th>
  </tr> 
  <tbody>
 <tr style="display:block;"> 
   <td>1</td> 
   <td>row 1</td> 
 </tr > 
<tr style="display:none;"> 
   <td>2</td> 
  <td>row 2</td> 
 </tr> 
<tr style="display:none;"> 
   <td>3</td> 
  <td>row 3</td> 
 </tr> 
 <tr style="display:none;"> 
   <td>4</td> 
  <td>row 4</td> 
 </tr> 
 <tr style="display:none;"> 
   <td>5</td> 
  <td>row 5</td> 
 </tr> 
 </tbody>
 </table>
 <button id="add">Add row</button>
 <button id="remove">Remove row</button>

Answer №2

Feel free to test out the code below!

I've included IDs for the add and remove buttons.

$('#btnAdd').click(function () { 
  $("table tr:hidden:first").show();
});

$('#btnRemove').click(function () {
   if($("table tr:visible").length !== 2) {
     $("table tr:visible:last").hide();
   }
});

Answer №3

Utilize this handy jQuery method to discover concealed table rows:

let hiddenRows = $("tr:hidden");

Afterwards, unveil one of them by executing the following code:

hiddenRows.first().show();

Answer №4

jQuery and Bootstrap Solutions

To implement jQuery solution, modify your buttons:

<button data-action="increase">Increase</button>
<button data-action="decrease">Decrease</button>

Then use the following script:

$(document).ready(function() { 
  $('button[data-action]').on('click', function() {

    // Check which button was clicked
    if ($(this).data('action') == 'increase') {

      // Show all table rows
      $('table td').parent().css('display', 'block');
    } else {

      // Hide all table rows
      $('table td').parent().css('display', 'none');
    }
  });
});

For the Bootstrap solution, adjust your table rows:

<tr style="height: 0px;"> 
  <td>5</td> 
  <td>row 5</td>
</tr>

Now you can apply this script:

$(document).ready(function() { 
  $('button[data-action]').on('click', function() {

    // Identify the clicked button
    if ($(this).data('action') == 'add') {

      // Show all 'tr' of 'td'
      $('table td').parent().collapse('show');
    } else {

      // Hide all 'tr' of 'td'
      $('table td').parent().collapse('hide');
    }
  });
});

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 it possible to employ the hide()/show() functions for elements that were concealed 'manually'?

In my upcoming project, I am planning to create a web page using JSP. To achieve the desired functionality, I want to hide an element in the JSP and then use jQuery to show it later. // This is how I have attempted to hide the div in the index.jsp file: & ...

Issue with JQuery executing PHP in Chrome extension

I have been attempting to retrieve the PHP result after using JQuery's post method within the context of a chrome extension. Unfortunately, all I am seeing is the unprocessed PHP code. Below is how I am calling the post method : $.post(chrome.extens ...

Modifying the attribute from "content-disposition:attachment" to "content-disposition:inline"

I created an HTML email signature that worked perfectly until I tested it in the Outlook Mail Client 2010, which is currently not displaying images but instead offering them as download attachments. I am utilizing DataUri for images: <img width="56" ...

Easily transfer files from your browser application to your Windows applications such as Outlook or printer queues using a simple drag and

I am attempting to transfer a downloaded file from a web browser to a Windows application (such as Outlook or a printer queue) by dragging and dropping. While I can successfully drop the file onto the desktop or any other file explorer location, I face iss ...

AngularJS Form Reverts Back to Original State After API Response

In my code, I am using a Factory with ng.resource: .factory('company', function($resource){ return $resource(appHelper.apiPath('auth/company/info'), {}, { update: { method: "PUT" } }); }); When submitting the form in m ...

Incorporating text into the border without increasing the spacing

I managed to create a unique CSS shape using clip paths as the border of a div. However, I am now facing an issue where I cannot add text to this border without it getting cut off due to the way the shape was created (possibly because of overflow: hidden). ...

What is the best way to add animation to switch between table rows?

I am looking to add animation effects when table rows appear and disappear. Initially, I attempted using a CSS transition, but it did not work due to the change in the display property. Subsequently, I opted for an animation, which provided the desired o ...

Guide on adding user input values (type=text) into HTML using JavaScript function outcome

I'm looking for a way to use the output of a JavaScript function as the value for an input field in HTML. Currently, I have a JavaScript function that generates a random string: function generateRandomString(length) { let result = ''; ...

Removing the last 3 elements using jQuery

My goal is to remove the label for Notes, text area of note and the checkbox near the text area, along with the delete button itself when the user clicks the delete button. I attempted to achieve this using the code snippet below, however it only removes t ...

Is the JSON object sent over an AJAX call getting corrupted during a POST request?

While conducting tests on this application, The browser is sending a json as an array of approximately 500 objects via POST method. Upon inspecting the received json using a PHP server and debugger(xdebug), It appears that there are more elements in ...

Tips on ensuring data cleanliness in jQuery input fields

Before sending the ajax request, I want to sanitize the form fields for added security. Currently, my Javascript code looks like this: jQuery(document).ready(function($) { $('#login-form').submit(function(e) { e.preventDefault(); // pr ...

Randomly swap out background images in multiple divs using JavaScript

I want to create a script that changes the background image of several divs every 3000ms with a fadeIn/fadeOut effect. I have 4 divs, each with their own background image All images are sourced from one array How can I achieve this? Here is the link to ...

Why does ajax transmit only the initial input value and not the rest of them?

I recently developed a school website where teachers can input students' marks. Currently, I have organized the project into three main files: The first file is designed to showcase every student's name based on their subject and course. <ta ...

Have the getter functions for reactive objects in Vue 3 been transformed into computed values?

Is the memoization of bookCount in this instance handled equivalently to a computed reference? const author = reactive({ name: 'John Doe', books: [ 'Vue 2 - Advanced Guide', 'Vue 3 - Basic Guide', 'Vue 4 - ...

Can logger with a specific name be segregated?

When I execute logger.debug('message'), the current output is as follows: {"message":"message","level":"debug"} Is there a way to modify the logger creation process so that the message structure looks more like this? {"message":"message","leve ...

Tips for resetting .one() functionality without needing to refresh the page

I have implemented a submit button with a .one() mouse event attached to it to prevent accidental double clicks from sending information twice. The issue arises when the containing div is refreshed after the information is sent (without refreshing the who ...

"Troubleshooting the Drupal module's PHP script location problem with jQuery

Currently, I am working on a module that includes a jQuery script along with some AJAX code. This ajax code is responsible for calling a php script which is located in the same directory as the jQuery script. The issue I'm facing right now is that wh ...

Is a directive necessary for a search element in this component?

I am currently learning angularJS and although it would be simpler to use JQuery for this task, I am determined to do it the right way. Essentially, I want to create a text input field where users can type in a search term, press a search button, and then ...

Updating Kendo Treeview's data source dynamically

I am working with a kendoTreeView connected to an OData source, following the demo on the official site. However, I encounter an issue when trying to change the dataSource of the kendoTreeView. Despite changing the tree successfully, all nodes are displaye ...

The functionality of switchClass() in jQuery is not compatible with the CSS :after selector

JSFiddle demo If you check out the JSFiddle demo and give it a try, you'll notice that while the blue bordered div disappears as intended, the text "Opened" doesn't change to "Closed" when using switchClass() with the :after selector. (Interesti ...