show/hide gridview columns in javascript

Hey just a quick snippet I came up with for showing/hiding table columns generated by grid view, usually helpful if the table is pretty wide. The script will read all the header names and create checkboxes and labels automatically.

Have a div someplace to hold all the checkboxes:

<p><a href="#showCols" id="showHide">Show/Hide table columns</a></p>

<script type="text/javascript">



		return false;



then after the call to grid view you can use this javascript (you’ll need to modify the main selectors to match your markup, but should be obvious):

<script type="text/javascript">

var $t = $('#leads-grid table.items');

var $h = $('thead tr:first th',$t).each(function(i) {

if(i < 2) return;

	var $i = $(this);

		var id = $i.attr('id');

		var text = $i.text();

		$('#showCols').append("<input type='checkbox' class='col-select' value='"+i+"' name='td_"+id+"' id='td_"+id+"' checked='checked'> ")

				.append("<label for='td_"+id+"'>"+text+"</label> <br>");



$('input.col-select').click(function() {

	var $i  = $(this);

	var val = parseInt($i.val()) + 1;		

	var $td = $('td:nth-child('+val+'), th:nth-child('+val+')', $t);		

	if($i.attr('checked')) {


	} else {





Just what I was looking for.

Thanks so much for sharing nsbucky.

thx for posting this.

sadly there is an issue, after an ajax refresh (e.g. page change) the "hidden" columns are again visible.

And i guess you should also add a container for your checkboxes to your sample code, so that someone without much js knowledge could test it.

<div id="showCols" style="display:none;"></div>