Javascript hide table row - Hide the row

Home - Tutorials - Miscellaneous

This article demonstrates how you can hide table row with javascript and how you can show it again by pressing a button.

Tutorial info:

Name:Javascript hide table row
Total steps:3
Product:See complete product

Bookmark Javascript hide table row

AddThis Social Bookmark Button

Step 2 - Hide the row

Javascript hide table row

If we want to work with only some row in the table then we need to identify these rows. To do this we will extend our html code and add an id property to the first <tr> tag. Let's call it captionRow. As mentioned before we also need a Javascript function to hide and show the relevant table row. Call this function to displayRow(). Now our code looks like this: 

  1. <table width="300" border="1">
  2. <tr id="captionRow"><th>TH-1</th><th>TH-2</th><th>TH-3</th></tr>
  3. <tr><td>cell-11</td><td>cell-12</td><td>cell-13</td></tr>
  4. <tr><td>cell-21</td><td>cell-22</td><td>cell-23</td></tr>
  5. </table>
  6. <p><button onclick="displayRow()" >Show / Hide</button></p>

As you can see the row is identified, a new button was added and a javascript function is called if the visitor press the button.

The javascript code 

The most important part of this article arrived. We need to implement the "magic" javascript function. As you will see it is quite simple.

First we need to get a reference to the selected row. We can do this by using the getElementById() function. So to skeleton of the code is the following:

  1. function displayRow(){
  2. var row = document.getElementById("captionRow");
  3. }

To continue we need to know that the <tr> tag has it's own style property. With this we can control if the given row should be displayed or not. For example to hide a row we can simply set the style to none as follows:

  2. = 'none';

Ok, but how we know if we need to hide or to show the actual row? It's quite simple just check the above mentioned value. So if it is set to none then we will set it to empty and vice verse. The complete javascript function to hide table row is quite simple:

  1. <script type="text/javascript">
  2. function displayRow(){
  3. var row = document.getElementById("captionRow");
  4. if ( == '') = 'none';
  5. else = '';
  6. }
  7. </script>

You can put the complete javascript block either in the head tag or just before the table code.

That's it! 

On the next page you will find the complete code and a working example.

Previous Step of Javascript hide table rowNext Step of Javascript hide table row

Tags: javascript hide table row, javascript hide table, javascript hide row, hide table row

Javascript hide table row - Table of contents
Step 1 - Introduction
Step 2 - Hide the row
Step 3 - Javascript hide row example and code

GAD Tower

Family tutorials
PHP Array
PHP Redirect
PHP Session
AJAX File Upload
AJAX Rating System
MySQL Create User
Mysqldump Example
MySQL Concat

Total time: 2.8903