Hide/Show Column In A HTML Table - Jquery - Stack Overflow

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Explore Teams Create a free Team
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs Hide/Show Column in a HTML Table Ask Question Asked 15 years, 5 months ago Modified 2 years, 3 months ago Viewed 359k times 163

I have an HTML table with several columns and I need to implement a column chooser using jQuery. When a user clicks on a checkbox I want to hide/show the corresponding column in the table. I would like to do this without attaching a class to every td in the table, is there a way to select an entire column using jQuery? Below is an example of the HTML.

<table> <thead> <tr><th class="col1">Header 1</th><th class="col2">Header 2</th><th class="col3">Header 3</th></tr> </thead> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> </table> <form> <input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br /> <input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br /> <input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br /> </form> Share Improve this question Follow edited Apr 3, 2022 at 4:01 Majid Basirati's user avatar Majid Basirati 2,8253 gold badges26 silver badges46 bronze badges asked Jan 18, 2009 at 21:46 Brian Fisher's user avatar Brian FisherBrian Fisher 23.8k15 gold badges79 silver badges82 bronze badges 3
  • 2 I hope the folowing site would help: fiendish.demon.co.uk/html/javascript/hidetablecols.htmluser344059 Commented May 18, 2010 at 13:22
  • I implemented this solution using jQuery, and it worked perfectly for me: http://www.devcurry.com/2009/07/hide-table-column-with-single-line-of.html – Aaron Commented Jul 6, 2010 at 17:23
  • 1 Per user344059's comment, here's the web archive for the broken link http://www.fiendish.demon.co.uk/html/javascript/hidetablecols.html – KyleMit Commented May 11, 2018 at 0:40
Add a comment |

9 Answers 9

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 274

One line of code using jQuery which hides the 2nd column:

$('td:nth-child(2)').hide();

If your table has header(th), use this:

$('td:nth-child(2),th:nth-child(2)').hide();

Source: Hide a Table Column with a Single line of jQuery code

jsFiddle to test the code: http://jsfiddle.net/mgMem/1/

If you want to see a good use case, take a look at my blog post:

Hide a table column and colorize rows based on value with jQuery.

Share Improve this answer Follow edited Mar 28, 2017 at 3:39 Matthew Lock's user avatar Matthew Lock 13.5k13 gold badges96 silver badges132 bronze badges answered May 5, 2011 at 16:50 Leniel Maccaferri's user avatar Leniel MaccaferriLeniel Maccaferri 102k46 gold badges375 silver badges492 bronze badges 10
  • 1 As an aside as they're not in the example, is there not an issue that this ignores colspans? Good if you're not using them though. There's another question related: stackoverflow.com/questions/1166452/… – Kim R Commented Nov 2, 2011 at 10:45
  • 2 I had to add the tbody to the selector to avoid hiding the footer with the pager: $('.webgrid tbody td:nth-child(1), .webgrid th:nth-child(1)').hide(); – Alex Commented Jan 12, 2012 at 22:54
  • @KimR This may help for colspan issues stackoverflow.com/questions/9623601/… – yunzen Commented Sep 26, 2012 at 10:13
  • I don't know exactly why, but I had to use 'nth-of-type' instead, to make it work. For example: $('table td:nth-of-type(2)').hide(); – Leopoldo Sanczyk Commented Oct 6, 2014 at 2:21
  • 1 @golimar yes... to restrict that, you need to add a CSS class to the table you want to target. Something as: .my-table-class td:nth-child(2) – Leniel Maccaferri Commented Oct 30, 2020 at 16:24
| Show 5 more comments 88

I would like to do this without attaching a class to every td

Personally, I would go with the the class-on-each-td/th/col approach. Then you can switch columns on and off using a single write to className on the container, assuming style rules like:

table.hide1 .col1 { display: none; } table.hide2 .col2 { display: none; } ...

This is going to be faster than any JS loop approach; for really long tables it can make a significant difference to responsiveness.

If you can get away with not supporting IE6, you could use adjacency selectors to avoid having to add the class attributes to tds. Or alternatively, if your concern is making the markup cleaner, you could add them from JavaScript automatically in an initialisation step.

Share Improve this answer Follow answered Jan 19, 2009 at 14:16 bobince's user avatar bobincebobince 534k109 gold badges665 silver badges840 bronze badges 3
  • 7 Thanks for the advice, I had wanted to keep the HTML cleaner, but performance definitely became an issue as the table size approached 100 rows. This solution, provided a 2-5x performance improvement. – Brian Fisher Commented Jan 23, 2009 at 7:04
  • 2 This approach worked wonders for me, performance-wise. Thanks! – axelarge Commented Apr 1, 2012 at 20:28
  • 4 I added this to my css .hidden {display:none;} and used .addClass('hidden') and .removeClass('hidden') which was a little faster than .hide() and .show(). – styfle Commented Dec 28, 2012 at 2:04
Add a comment | 19

Here's a little more fully featured answer that provides some user interaction on a per column basis. If this is going to be a dynamic experience, there needs to be a clickable toggle on each column that indicates the ability to hide the column, and then a way to restore previously hidden columns.

That would look something like this in JavaScript:

$('.hide-column').click(function(e){ var $btn = $(this); var $cell = $btn.closest('th,td') var $table = $btn.closest('table') // get cell location - https://stackoverflow.com/a/4999018/1366033 var cellIndex = $cell[0].cellIndex + 1; $table.find(".show-column-footer").show() $table.find("tbody tr, thead tr") .children(":nth-child("+cellIndex+")") .hide() }) $(".show-column-footer").click(function(e) { var $table = $(this).closest('table') $table.find(".show-column-footer").hide() $table.find("th, td").show() })

To support this, we'll add some markup to the table. In each column header, we can add something like this to provide a visual indicator of something clickable

<button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column"> <i class="fa fa-eye-slash"></i> </button>

We'll allow the user to restore columns via a link in the table footer. If it's not persistent by default, then toggling it on dynamically in the header could jostle around the table, but you can really put it anywhere you'd like:

<tfoot class="show-column-footer"> <tr> <th colspan="4"><a class="show-column" href="#">Some columns hidden - click to show all</a></th> </tr> </tfoot>

That's the basic functionality. Here's a demo below with a couple more things fleshed out. You can also add a tooltip to the button to help clarify its purpose, style the button a little more organically to a table header, and collapse the column width in order to add some (somewhat wonky) css animations to make the transition a little less jumpy.

Demo Screengrab

Working Demo in jsFiddle & Stack Snippets:

$(function() { // on init $(".table-hideable .hide-col").each(HideColumnIndex); // on click $('.hide-column').click(HideColumnIndex) function HideColumnIndex() { var $el = $(this); var $cell = $el.closest('th,td') var $table = $cell.closest('table') // get cell location - https://stackoverflow.com/a/4999018/1366033 var colIndex = $cell[0].cellIndex + 1; // find and hide col index $table.find("tbody tr, thead tr") .children(":nth-child(" + colIndex + ")") .addClass('hide-col'); // show restore footer $table.find(".footer-restore-columns").show() } // restore columns footer $(".restore-columns").click(function(e) { var $table = $(this).closest('table') $table.find(".footer-restore-columns").hide() $table.find("th, td") .removeClass('hide-col'); }) $('[data-toggle="tooltip"]').tooltip({ trigger: 'hover' }) }) body { padding: 15px; } .table-hideable td, .table-hideable th { width: auto; transition: width .5s, margin .5s; } .btn-condensed.btn-condensed { padding: 0 5px; box-shadow: none; } /* use class to have a little animation */ .hide-col { width: 0px !important; height: 0px !important; display: block !important; overflow: hidden !important; margin: 0 !important; padding: 0 !important; border: none !important; } <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/paper/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <table class="table table-condensed table-hover table-bordered table-striped table-hideable"> <thead> <tr> <th> Controller <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column"> <i class="fa fa-eye-slash"></i> </button> </th> <th class="hide-col"> Action <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column"> <i class="fa fa-eye-slash"></i> </button> </th> <th> Type <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column"> <i class="fa fa-eye-slash"></i> </button> </th> <th> Attributes <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column"> <i class="fa fa-eye-slash"></i> </button> </th> </thead> <tbody> <tr> <td>Home</td> <td>Index</td> <td>ActionResult</td> <td>Authorize</td> </tr> <tr> <td>Client</td> <td>Index</td> <td>ActionResult</td> <td>Authorize</td> </tr> <tr> <td>Client</td> <td>Edit</td> <td>ActionResult</td> <td>Authorize</td> </tr> </tbody> <tfoot class="footer-restore-columns"> <tr> <th colspan="4"><a class="restore-columns" href="#">Some columns hidden - click to show all</a></th> </tr> </tfoot> </table>

Share Improve this answer Follow edited Nov 23, 2018 at 14:43 answered Jan 23, 2018 at 20:48 KyleMit's user avatar KyleMitKyleMit 34.2k72 gold badges488 silver badges685 bronze badges 7
  • you are hiding nearest 1 column,how to hide nearest 3 column ? – Nirmal Goswami Commented Jun 15, 2018 at 4:38
  • check my table - i.sstatic.net/AA8iZ.png and question which contain table html - stackoverflow.com/questions/50838119/… button will come after A,B and C – Nirmal Goswami Commented Jun 15, 2018 at 4:51
  • sorry to revive such an old answer, but is there an easy way of setting certain columns to hidden by default? I'm trying to do so with $(document).ready but having no luck – RobotJohnny Commented Nov 22, 2018 at 12:24
  • 1 @RobotJohnny, good question. This is using the class .hide-col to remove columns, but it can also be used to indicate state as well, so you could either - add .hide-col to each td & tr when rendering the html and be done. Or if you wanted to add it in fewer places, put it in the header (that state will have to go somewhere), and on init, use that to hide that column index across children. Currently, the code is just listening for the the position on click, but it could be modified to look for class position as well. Also, happy turkey day – KyleMit Commented Nov 22, 2018 at 13:13
  • 1 @RobotJohnny, I updated the code sample to include initialization handling as well. Just drop class='hide-col' anywhere you want in your html (probably in in the thead > tr > th makes the most sense and it will pick up to make sure it hides all cells in that column and dynamically show the restore footer as well – KyleMit Commented Nov 23, 2018 at 14:46
| Show 2 more comments 12

you could use colgroups:

<table> <colgroup> <col class="visible_class"/> <col class="visible_class"/> <col class="invisible_class"/> </colgroup> <thead> <tr><th class="col1">Header 1</th><th class="col2">Header 2</th><th class="col3">Header 3</th></tr> </thead> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> </table>

your script then could change just the desire <col> class.

Share Improve this answer Follow answered Jan 18, 2009 at 21:52 Luis Melgratti's user avatar Luis MelgrattiLuis Melgratti 12k3 gold badges32 silver badges32 bronze badges 5
  • I seem to remember colgroup not having cross browser support is that no longer true? – Brian Fisher Commented Jan 18, 2009 at 22:03
  • Maybe. i'm using this method for hilight columns, (firefox, safari, chrome works fine) never tried it in IE. – Luis Melgratti Commented Jan 18, 2009 at 22:12
  • @Brian - IE8 does not work and IE8 with IE7 enabled seems to be working. – Nordes Commented Aug 23, 2010 at 7:43
  • 4 This seems not to work anymore in modern browser (Chrome and Firefox) – JBE Commented Feb 28, 2013 at 14:57
  • 1 @JBE: to be precise, this does work in modern browsers to some extent. Using the $('table > colgroup > col.yourClassHere') jQuery selector, you still can set smth like the background color of the whole column, but you're no longer able to toggle column visibility. Browsers tested were MSIE 11, Safari 5, Chromium 44, Opera 12, Mozilla SeaMonkey 2.40, Mozilla Firefox 43. "Most of the attributes in HTML 4.01 are not supported in HTML5" -- see here. – Bass Commented Apr 28, 2016 at 16:41
Add a comment | 11

The following should do it:

$("input[type='checkbox']").click(function() { var index = $(this).attr('name').substr(2); $('table tr').each(function() { $('td:eq(' + index + ')',this).toggle(); }); });

This is untested code, but the principle is that you choose the table cell in each row that corresponds to the chosen index extracted from the checkbox name. You could of course limit the selectors with a class or an ID.

Share Improve this answer Follow edited Jan 18, 2009 at 22:03 answered Jan 18, 2009 at 21:57 Eran Galperin's user avatar Eran GalperinEran Galperin 86.6k24 gold badges117 silver badges132 bronze badges Add a comment | 5

And of course, the CSS only way for browsers that support nth-child:

table td:nth-child(2) { display: none; }

This is for IE9 and newer.

For your usecase, you'd need several classes to hide the columns:

.hideCol1 td:nth-child(1) { display: none;} .hideCol2 td:nth-child(2) { display: none;}

ect...

Share Improve this answer Follow edited Oct 31, 2014 at 8:40 answered May 18, 2014 at 13:28 ProblemsOfSumit's user avatar ProblemsOfSumitProblemsOfSumit 20.9k9 gold badges53 silver badges65 bronze badges Add a comment | 2

The following is building on Eran's code, with a few minor changes. Tested it and it seems to work fine on Firefox 3, IE7.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <script> $(document).ready(function() { $('input[type="checkbox"]').click(function() { var index = $(this).attr('name').substr(3); index--; $('table tr').each(function() { $('td:eq(' + index + ')',this).toggle(); }); $('th.' + $(this).attr('name')).toggle(); }); }); </script> <body> <table> <thead> <tr> <th class="col1">Header 1</th> <th class="col2">Header 2</th> <th class="col3">Header 3</th> </tr> </thead> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr> </table> <form> <input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br /> <input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br /> <input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br /> </form> </body> </html> Share Improve this answer Follow answered Jan 18, 2009 at 22:15 Paolo Bergantino's user avatar Paolo BergantinoPaolo Bergantino 486k82 gold badges519 silver badges437 bronze badges Add a comment | 1 <p><input type="checkbox" name="ch1" checked="checked" /> First Name</p> .... <td class="ch1">...</td> <script> $(document).ready(function() { $('#demo').multiselect(); }); $("input:checkbox:not(:checked)").each(function() { var column = "table ." + $(this).attr("name"); $(column).hide(); }); $("input:checkbox").click(function(){ var column = "table ." + $(this).attr("name"); $(column).toggle(); }); </script> Share Improve this answer Follow answered Jun 2, 2015 at 8:08 lahbib's user avatar lahbiblahbib 1191 silver badge6 bronze badges Add a comment | 0

Without class? You can use the Tag then:

var tds = document.getElementsByTagName('TD'),i; for (i in tds) { tds[i].style.display = 'none'; }

And to show them use:

...style.display = 'table-cell'; Share Improve this answer Follow answered Aug 13, 2013 at 16:32 Gustavo Ruiz's user avatar Gustavo RuizGustavo Ruiz 6855 silver badges4 bronze badges Add a comment |

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved Draft discarded

Sign up or log in

Sign up using Google Sign up using Email and Password Submit

Post as a guest

Name Email

Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • The Overflow Blog
  • How to build open source apps in a highly regulated industry
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • What makes a homepage useful for logged-in users
  • The [lib] tag is being burninated

Linked

23 Finding column index using jQuery when table contains column-spanning cells 8 Get Cell Location 5 How to use class attribute in html col 4 How to hide a column in the Webgrid in aspasp.net MVC? 5 Collapse/Expand table columns (not rows) 2 Hiding middle columns of html table with jQuery 1 Jquery .Toggle() based on colgroup col id 1 Remove column from specific table with JQuery 2 Attempting to hide a column of a html table using jQuery 1 How Do I Use JQuery To Hide And Show Columns In An HTML Table? See more linked questions 1 Hide/show table columns with jQuery 6 How to hide table columns in jQuery? 11 hide column/td of the table by using jquery 2 Table show/hide columns 2 Hide a table column using jQuery 1 jquery how to show-hide table column 2 Attempting to hide a column of a html table using jQuery 1 How Do I Use JQuery To Hide And Show Columns In An HTML Table? 1 Show and hide table column using jQuery 0 JQuery hide table column

Hot Network Questions

  • Book in 90's (?) about rewriting your own genetic code
  • Why do I see low voltage in a repaired underground cable?
  • spath3 rotations shrink paths
  • Wait a minute, this *is* 1 across!
  • How much time do I need on my Passport expiry date to leave Australia for South Africa?
  • What does '\($*\)' mean in sed regular expression in a makefile?
  • Identify rear derailleur (Shimano 105 - medium or short)
  • Can you arrange 25 whole numbers (not necessarily all different) so that the sum of any three successive terms is even but the sum of all 25 is odd?
  • What is meant by "blue ribbon"?
  • Is there a drawback to using Heart's blood rote repeatedly?
  • Can you help me to identify the aircraft in a 1920s photograph?
  • Seeing edges where there are no edges
  • How to maintain dependencies shared among microservices?
  • Ideal diode in parallel with resistor and voltage source
  • Why didn't Jimmy Neutron realize immediately when he read the note on the refrigerator that the note is phony, as the note says "son or daughter..."?
  • If a lambda is declared as a default argument, is it different for each call site?
  • 6 balls, one is either heavier or lighter, find the odd ball in minimum weighings
  • Why does the Trump immunity decision further delay the trial?
  • Is it possible to arrange the free n-minoes of orders 2, 3, 4 and 5 into a rectangle?
  • Could someone translate & explain the Mesorah?
  • Books using the axiomatic method
  • What are these courtesy names and given names? - confusion in translation
  • Evil God Challenge: What if an evil god is just trolling humanity and that explains why there's good in the world?
  • What's the point of Dream Chaser?
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

default

Từ khóa » Html Table Hide Column Dynamically