Supporters of End User
Web

SharePoint: Toggle column visibility in list view

 
Item is currently unrated. Press SHIFT+ENTER to rate this item.1 star selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+ESCAPE to leave rating submit mode.2 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.3 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.4 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.5 stars selected. Press SHIFT+ENTER to submit. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.
Categories: 

Guest Author: Alexander Bautz
SharePoint JavaScripts

7/26/2010: Alexander has updated the following items: Modified code to support multiple list views in the same page. The code is not fully tested so please report any bugs. Only the code for the file ToggleColumnVisibility.js� has changed. Modified code to support �pre hiding� from query string parameter. Both the CEWP code and the file �ToggleColumnVisibility.js� has changed.

Here are a solution for toggling the columns visibility in a list view by adding a checkbox row above the list view. Remove the check to hide the column. recheck to show.

The solution dynamically adapts to the columns in the view.

As always we start like this:

Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of �/test/English/Javascript� (a sub site named �test� with a sub site named �English� with a document library named �Javascript�):

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.4.2.min. If you download another version, please update the code in the CEWP.

The sourcecode for the file �ToggleColumnVisibility.js� is provided below.

Add this code to a CEWP below the list view:

<script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/ToggleColumnVisibility.js"></script>
<script type="text/javascript">
// To "pre uncheck" checkboxes, add names to this array
	var arrOfPreHiddenColumns = ['MyPeoplePicker','My multi line'];
// Pull columns to "pre uncheck" from the query string parameter "ColumnsToHide"
	var qStrPAram = getQueryParameters();
	var colFromQueryString = qStrPAram.ColumnsToHide;
	if(colFromQueryString!=undefined){
		arrOfPreHiddenColumns = arrOfPreHiddenColumns.concat(colFromQueryString.split(','));
	}
	init_Checkboxes(arrOfPreHiddenColumns);
</script>

Regarding the variable �arrOfPreHiddenColumns�:

Refer fields by their FieldInternalName. The �Edit� button and multi line test fields however does not have their FieldIternalName present in the column header and therefore must be addressed by their DisplayName.

Passing columns to hide in the query string:

To hide columns by query string, pass them in the URL like this:
/test/English/Lists/ToggleColumnVisibility/AllItems.aspx?ColumnsToHide=MyNumberColumn,ID

The sourcecode for the file �ToggleColumnVisibility.js�:

/* Renders a line of checkboxes above the list view to toggle column visibility
 * -----------------------------
 * Author: Alexander Bautz
 * alexander.bautz@gmail.com
 * http://sharepointjavascript.wordpress.com
 * Version: 1.2
 * LastMod: 19.05.2010
 * LastChange: Added support for multiple webparts in the same view
 * -----------------------------
 * Must include reference to jQuery - http://jquery.com
 * ----------------------------------------------------
*/

function init_Checkboxes(arrOfPreHidden){
$(".ms-listviewtable").each(function(){
	var thisTable = $(this);
	var arrFields = [];
	thisTable.find(".ms-viewheadertr >*[class^='ms-v']").each(function(){
	if($(this).hasClass('ms-vh-group'))return;
		var disp = $(this).find('table:first').attr('displayname');
		var fin = $(this).find('table:first').attr('name');
		if(disp==null){
			disp = $(this).html().match(/^[a-z|A-Z|0-9|\s]+/).toString();
		}
		if(fin==null){
			fin = disp;
		}
		if($.inArray(fin,arrOfPreHidden)==-1){
			checked = "checked='true'";
		}else{
			checked = "";
		}
		var cindex = $(this).attr('cellIndex');
		$(this).attr('cindex',cindex);
		arrFields.push("<span>");
		arrFields.push("<input id='customCheckbox_"+cindex+"' title='Toggle visibilty for "+disp+"' ");
		arrFields.push("type='checkbox' cindex='"+cindex+"' onclick='javascript:hideColumn($(this))' "+checked+" />");
		arrFields.push("<label for='customCheckbox_"+cindex+"' >"+disp+"&nbsp;</label></span>");
	});
	arrFields = "<div style='font-size:11px' class='customToggleColumnCheckbox'>"+arrFields.join('')+"</div>";
	thisTable.before(arrFields);
	// Hide unchecked
	init_HideColumn();
	});
}

function init_HideColumn(){
	// Group expansion
	var checkboxes = $(".customToggleColumnCheckbox").find('input:checkbox');
	$.each(checkboxes,function(){
		if($(this).attr('checked')==false){
			hideColumn($(this));
		}
	});
}

function hideColumn(obj){
	var thisListViewTable = obj.parents("div[id^='WebPartWPQ']");
	toggleCol = obj.attr('checked');
	cindex = obj.attr('cindex');
	var thToToggle =  thisListViewTable.find(".ms-viewheadertr >*[class^='ms-v']").eq(cindex);
	if(!toggleCol){
		thToToggle.hide();
	}else{
		thToToggle.show();
	}
	thisListViewTable.find("table.ms-listviewtable >tbody >tr").each(function(){
		var tdToToggle = $(this).find(">td:eq("+cindex+")");
		if(!toggleCol){
			tdToToggle.hide();
		}else{
			tdToToggle.show();
		}
	});
}
// Function to separate each url search string parameters
function getQueryParameters(){
qObj = {};
var urlSearch = window.location.search;
	if(urlSearch.length>0){
		var qpart = urlSearch.substring(1).split('&');
		$.each(qpart,function(i,item){
			var splitAgain = item.split('=');
			qObj[splitAgain[0]] = splitAgain[1];
		});
	}
return qObj;
}

// Attaches a call to the function to the "expand grouped elements function" for it to function in grouped listview's
function ExpGroupRenderData(htmlToRender, groupName, isLoaded){
	var tbody=document.getElementById("tbod"+groupName+"_");
	var wrapDiv=document.createElement("DIV");
	wrapDiv.innerHTML="<TABLE><TBODY id=\"tbod"+groupName+"_\" isLoaded=\""+isLoaded+"\">"+htmlToRender+"</TBODY></TABLE>";
	tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild,tbody);
	init_HideColumn();
}

Save as �ToggleColumnVisibility.js�, mind the file extension, and upload to the scriptlibrary as shown above.

Ask if anything is unclear.

Guest Author: Alexander Bautz
SharePoint JavaScripts

Alexander Bautz is a SharePoint consultant/developer (mainly JavaScript/jQuery solution) living in Norway. Alexander spends a lot of his spare time blogging on the same topics. His focus area is "end user customizations" with no (or as little as possible) server side code.

[tweet]

Comments

George W

SharePoint: Toggle column visibility in list view

WOW ! HS !!! Well done!

Posted 23-Apr-2010 by George W
pat

SharePoint: Toggle column visibility in list view

This is a very cool feature!

Posted 23-Apr-2010 by pat
Mike

SharePoint: Toggle column visibility in list view

Is it possible for this to work in a dataview? - When I convert the list to XSLT Datview the checkboxes disappear..

Posted 27-Apr-2010 by Mike
Mike

SharePoint: Toggle column visibility in list view

I figured it out. You can delete my question. This is great by the way.

Posted 27-Apr-2010 by Mike
Mary

SharePoint: Toggle column visibility in list view

Related but not exactly on-topic: Can I get the ID column to appear on the list item view or list item edit pages? I can add the ID column to VIEWS, but I can't seem to add it to the list item view or edit.

Posted 07-May-2010 by Mary
Bill Garvey

SharePoint: Toggle column visibility in list view

Excellent - love it!!

Works like a charm!!

Posted 12-May-2010 by Bill Garvey
Arkadiy Birger

SharePoint: Toggle column visibility in list view

would you please share? generally there is Hide content menu item, but another way of doing it would be nice too

Posted 13-May-2010 by Arkadiy Birger
Niall

SharePoint: Toggle column visibility in list view

Excellent script!

I've set a pre unchecked hidden field using:
var arrOfPreHiddenColumns =

How can I make it so the header with the check boxes for displaying the fields does not display? I'm using this script so I can use filtering with Connections, Provide Row To but without displaying the field that is being sorted by (which works fine using the script just I don't want the tick boxes to appear at the top).

Posted 14-May-2010 by Niall
Steve

SharePoint: Toggle column visibility in list view

How would this be done without the checkboxes (for the case when the fields to be hiden are known in advance and never change); the arrOfPreHiddenColumns could be permanently set in the CEWP. There would probably be a lot less code. Thanks!!

Posted 17-May-2010 by Steve
Bill Garvey

SharePoint: Toggle column visibility in list view

If you always want to hide the same columns, wouldn't you just create a view and not include the columns? That would be truly a no-code solution.

I could see wanting to hide the checkboxes, and pass the array of columns to hide in the URL.

Posted 17-May-2010 by Bill Garvey
Niall

SharePoint: Toggle column visibility in list view

Hi Bill, The reason I'm wanting to do this is that you can filter data that is being displayed in the list, from another web part using the connections property, so with this script it allows this but keeps the field hidden. This can't be done if the column is not included in the view.

Posted 17-May-2010 by Niall
Bill Garvey

SharePoint: Toggle column visibility in list view

Gotcha - as a matter of fact, I have a similar need where I want to pass a URL parameter to a page, but the list has to have the column (which I do not want!)

I eagerly await to see if a solution is acheived.

Bill

Posted 17-May-2010 by Bill Garvey
David Hamilton

SharePoint: Toggle column visibility in list view

Not showing anything at all.

The Script Library is in a top level site, and the CEWP code points to that location. I have tried this with absolute and relative references, makes no difference.

Creates a special page for the list, placed the CEWP below or above the list. Makes no difference.

Made sure that Full Toolbar was on (per your example).

Nothing shows above the Toolbar.

Any thoughts about this? Potential mistakes?

Posted 18-May-2010 by David Hamilton
David Hamilton

SharePoint: Toggle column visibility in list view

Never mind. Copying the code with line numbers screws it up. Better to view source and copy that, as you suggested.

Posted 18-May-2010 by David Hamilton
Bill Garvey

SharePoint: Toggle column visibility in list view

When you refer to script, are you only referring to the jQuery and ToggleColumnVisibility scripts, or are you placing the content of the CEWP in a text file, and calling that using "Content Link"

I have found that if you try and call a CEWP script that is not on the site (i.e. using the "Content Link" in the CEWP) the location where the script resides MUST have anonymous access turned on:

http://office.microsoft.com/en-us/sharepointserver/HA100240461033.aspx

"If the Content Link property links to a file that is located outside the site and the site does not have anonymous user access enabled, you cannot access the file. For assistance, contact your site administrator."

I believe even if you are in the same collection, you must have it turned on. So if you are calling, using "Content Link", a script that in on the top level, you may need to turn on anonymous access to that folder.

Sorry if this is not your situation. I am able to load the CEWP content in via source editor, and point to the jQuery and Toggle scripts using fully qualified URLs of an offsite "resource center" with no problems.

Posted 18-May-2010 by Bill Garvey
EndUserSharePoint

SharePoint: Toggle column visibility in list view

David - Mouse over the code. A context menu pops up in the right hand corner. Click the "Code" icon and it will open in plan text view for copying. -- Mark

Posted 18-May-2010 by EndUserSharePoint
Mike

SharePoint: Toggle column visibility in list view

This is really impressive. I love it! My users will drool all over this feature.

Posted 18-May-2010 by Mike
Ben

SharePoint: Toggle column visibility in list view

This is very tidy code, pretty much covered everything you can think of, I especially like the including the refresh of hidden details on group expansions.

However I had a slight problem when dropping multiple list views on a page. I found that whilst the content of the columns were hidden in every list view the column header was only hidden on the first list view.

I got round this by writing my own code to recursively look through and hide each of the column headers.

The issue was with function hidecolumn it hides the column header and then all content. But whilst it finds each content cell (and by that rule hides every instance in every web part) it only does the first column header.

I have only started hacking with Jquery and javascript over the past week or so, so it's not very elegant but I got round it by doing this.... (I had to hard code the column header name)

$(".ms-viewheadertr >*[class^='ms-v']").each(function(){
var thToToggle = $(this).find("[name*='Profiles']");
thToToggle.hide();

});

Posted 18-May-2010 by Ben
Marta

SharePoint: Toggle column visibility in list view

Hi Bill,
a question, is there a limit to the number fo columns?
I cannot make it work in my list view, there is no error message. All the links and reference to .js seem to be correct but yet the checkboxes don't appear.

My CEWP script below:

// To "pre uncheck" checkboxes, add names to this array
var arrOfPreHiddenColumns = ['Customer name',Customer number','Sales Manager','Country','City',Core Segment','Subsegment','Technology','Specific Techn','End Use','Est Close Yr','Est Close Qtr','Opp Status','Sales Status','Est Current Year €K','Est Annual €K','Est Annual Volume','Sales Comment','Competitor','Incumbent','WonLoss','Won/Loss Reason','LWR Number','EMEA Region','Carry over','Created By','Modified By'];

// Pull columns to "pre uncheck" from the query string parameter "ColumnsToHide"
var qStrPAram = getQueryParameters();
var colFromQueryString = qStrPAram.ColumnsToHide;
if(colFromQueryString!=undefined){
arrOfPreHiddenColumns = arrOfPreHiddenColumns.concat(colFromQueryString.split(','));
}
init_Checkboxes(arrOfPreHiddenColumns);

Posted 16-Jun-2010 by Marta
Marta

SharePoint: Toggle column visibility in list view

sorry don't know why it did not get pasted all the last time




// To "pre uncheck" checkboxes, add names to this array
var arrOfPreHiddenColumns = ['Customer name',Customer number','Sales Manager','Country','City',Core Segment','Subsegment','Technology','Specific Techn','End Use','Est Close Yr','Est Close Qtr','Opp Status','Sales Status','Est Current Year €K','Est Annual €K','Est Annual Volume','Sales Comment','Competitor','Incumbent','WonLoss','Won/Loss Reason','LWR Number','EMEA Region','Carry over','Created By','Modified By'];

// Pull columns to "pre uncheck" from the query string parameter "ColumnsToHide"
var qStrPAram = getQueryParameters();
var colFromQueryString = qStrPAram.ColumnsToHide;
if(colFromQueryString!=undefined){
arrOfPreHiddenColumns = arrOfPreHiddenColumns.concat(colFromQueryString.split(','));
}
init_Checkboxes(arrOfPreHiddenColumns);

Posted 16-Jun-2010 by Marta
Scott

SharePoint: Toggle column visibility in list view

I found your code while trying to search for a solution for something that I am trying to do in SharePoint. I was wondering if your code could be used for my solution with some minor tweaks or if I should be looking for something totally different. Basically, we want to create a page that shows a list of courses, and then when you click on a course, the description shows up. Initially, I was thinking to create a list of the courses, and then tie that into another web part that just had the descriptions in there. When you click on the course, then it would display the description. Both web parts would be on the same page. I then saw your code here, and thought that maybe it doesn't have to be that complicated, that we could show the list of course with the checkboxes, and then when clicked, it would show the description. That would require changes to hide/unhide rows instead of columns. Is that an easy modification? Am I off base on this?
I am a novice developer, so I understand some not all about how the code is written. I know that it looks for the first table and grabs the display names of the columns. For the rows, I see that the unique identification for the rows is the ID name, but not sure how to incorporate that.

Any help you can give is greatly appreciated!

Posted 26-Jul-2010 by Scott
Ron

SharePoint: Toggle column visibility in list view

I've followed the insturctions but have had no luck with this.  Is there a way to verify that the ToggleColumnVisibility.js is opening?  I tried puttling in a simple alert('hello') after the jquery and It works but after the togglecolumnvisibility.js Im not getting the pop up. 

Posted 11-May-2011 by Ron
ron

SharePoint: Toggle column visibility in list view

GOT IT!  This works great.  Thank you so much.

Posted 11-May-2011 by ron

Notify me of comments to this article

E-mail:
   

Add Comment

Title:

 
Comment:
Email:

   


Name:

 
Url: