1,516 articles and 10,676 comments as of Tuesday, April 27th, 2010

Friday, April 23, 2010

SharePoint: Toggle column visibility in list view

Guest Author: Alexander Bautz
SharePoint JavaScripts

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.1
 * LastMod: 19.04.2010
 * LastChange: Added option for hiding columns based on querystring parameters
 * -----------------------------
 * Must include reference to jQuery - http://jquery.com
 * ----------------------------------------------------
*/

function init_Checkboxes(arrOfPreHidden){
var arrFields = [];
$(".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 id='customToggleColumnCheckbox'>"+arrFields.join('')+"</div>";
$(".ms-bodyareaframe").prepend(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){
	toggleCol = obj.attr('checked');
	cindex = obj.attr('cindex');
	var thToToggle = $(".ms-viewheadertr >*[class^='ms-v']").eq(cindex);
	if(!toggleCol){
		thToToggle.hide();
	}else{
		thToToggle.show();
	}
	$("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

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

    WOW ! HS !!! Well done!

    Like? Thumb up 0 Thumb down 1

  2. pat says:

    This is a very cool feature!

    Like? Thumb up 0 Thumb down 1


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!