How to Show Hide Toggle Table Column Using Jquery

 Posted On  | Yashwant Chavan 

Recently I am working on Jquery :nth-child() selector part while working on this, I remember few year back I did the similar kind of functionality using javascript. The requirement was show and hide the report column on the basis of check box selection.

Because my report contains large number of columns, near about 30 to 40 columns. So my client want to hide or show report columns on selection of check-boxes. So our today's article is base on the same requirement. With the help of Jquery selector its possible to do using single line of code.

Jquery :nth-child() Selector

This selector is used to selects all elements that are the nth-child of their parent. In below example we simply select the 3 column till its nth child.like $('td:nth-child(3)').hide(); and on that selector we use .hide() and .show() and .toggle() methods.

Which hide, show and toggle the column behavior. You can find more information about this selector on official website of jquery. Please go through this topic it will give you more knowledge on selectors part. (http://api.jquery.com/nth-child-selector/)

Useful to whom This tutorial is useful for beginners and experience jquery developers, who wants to learn more about jquery selectors with live examples.

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
 <head>
  <style>
Table.GridOne {
 padding: 3px;
 margin: 0;
 background: lightyellow;
 border-collapse: collapse; 
 width:45%;
}

Table.GridOne Td { 
 padding:2px;
 border: 1px solid #ff9900;
 border-collapse: collapse;
}
</style>
  <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
  <script>
    $(function() {
       $('#hide').click(function() {
                $('td:nth-child(3)').hide();                
       });

    $('#show').click(function() {
                $('td:nth-child(3)').show();                
       });
    $('#toggle').click(function() {
                $('td:nth-child(3)').toggle();                
       });
    });
    </script>
 </HEAD>

 <body>
  <table class="GridOne">
   <tr>
  <td>Heading 1</td>
  <td>Heading 2</td>
  <td>Heading 3</td>
  <td>Heading 4</td>
   </tr>
   <tr>
  <td>Value 1</td>
  <td>Value 2</td>
  <td>Value 3</td>
  <td>Value 4</td>
   </tr>
   <tr>
  <td>Value 1</td>
  <td>Value 2</td>
  <td>Value 3</td>
  <td>Value 4</td>
   </tr>
  </table>

  <input id="hide" type="button" value="Hide 3rd Column"/> <input id="show" type="button" value="Show 3rd Column"/> <input id="toggle" type="button" value="Toggle 3rd Column"/>
 </body>
</html>

In live demo there are three buttons which hide, show and toggle the Third column of table.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0267 seconds.