1,804 articles and 14,889 comments as of Monday, April 25th, 2011

EndUserSharePoint has combined resources with NothingButSharePoint.com. You can now find End User (Mark Miller), Developer (Jeremy Thake) and IT Pro SharePoint (Joel Oleson) content all in one place!

This site is a historical archive and is no longer being updated. Please update your favorites, bookmarks and RSS feeds.

NothingButSharePoint.com
Friday, April 23, 2010

SharePoint: Toggle column visibility in list view

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
 * [email protected]
 * 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.

 

Please Join the Discussion

23 Responses to “SharePoint: Toggle column visibility in list view”
  1. George W says:

    WOW ! HS !!! Well done!

  2. pat says:

    This is a very cool feature!

  3. Mike says:

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

    • Mike says:

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

      • Arkadiy Birger says:

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

  4. Mary says:

    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.

  5. Bill Garvey says:

    Excellent – love it!!

    Works like a charm!!

  6. Niall says:

    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).

  7. Steve says:

    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!!

    • Bill Garvey says:

      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.

  8. Niall says:

    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.

    • Bill Garvey says:

      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

  9. 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?

    • Bill Garvey says:

      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.

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

  11. Mike says:

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

  12. Ben says:

    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 &gt;*[class^='ms-v']").each(function(){
        var thToToggle = $(this).find("[name*='Profiles']");
       thToToggle.hide();
    
        });
    
  13. Marta says:

    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);
    
  14. Marta says:

    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);

  15. Scott says:

    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!

  16. William says:

    Dear all,

    Can this script work in SharePoint 2010

  17. Phebe says:

    I have tried this in SP 2010 but haven’t been able to get it to work. Created a library called “Javascript” and placed both the script files as well as the text file containing the code for CEWP webpart.
    Added a CEWP webpart with link to the .txt file, under the list view for a Custom List but no results.
    Please help!


Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!