Toggle column visibility in list view

25.08.2011 I have ported this to SharePoint 2010. The instruction for use is the same as for v1.4 for SharePoint 2007. You find the code in the download section.


24.08.2011 I have released a new version (v1.4) that adds the following new feature requested by Bill G:
Added a new parameter “arrDoNotRender”. This is an array of fields passed as an argument to the function “init_Checkboxes”.
The fields in this array will not render as a checkbox, but can be prehidden using the array “arrOfPreHiddenColumns” or passed as an argument in the URL.

There are changes to:
The file “ToggleColumnVisibility.js” and the CEWP-code.


Change log:

30.08.2010 Added the ability to skip one or more columns by adding them to the array “arrOfFieldInternalNamesToSkip”. Both the CEWP code and the file “ToggleColumnVisibility.js” has changed.

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

19.04.2010 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.
IMG

IMG

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”):
IMG

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:
For v1.3
[javascript]
<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(‘,’));
}
// Array of columns to skip
var arrOfFieldInternalNamesToSkip = [];
// Call the script
init_Checkboxes(arrOfPreHiddenColumns,arrOfFieldInternalNamesToSkip);
</script>
[/javascript]

For v1.4 on SP2007 and 1.x on SP2010
[javascript]
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/ToggleColumnVisibility/ToggleColumnVisibility.js"></script>
<script type="text/javascript">
// To "pre uncheck" checkboxes, add names to this array
var arrOfPreHiddenColumns = [‘MyPeoplePicker’,’My multi line’,’ID’];
// Array of columns to skip
var arrOfFieldInternalNamesToSkip = [];
// Array of columns that will not render a checkbox
var arrDoNotRenderCheckbox = [‘LinkTitle’,’ID’];

// Call the script
init_Checkboxes(arrOfPreHiddenColumns,arrOfFieldInternalNamesToSkip,arrDoNotRenderCheckbox);
</script>
[/javascript]

Regarding the variable “arrOfPreHiddenColumns”:
Refer fields by their FieldInternalName. The “Edit” button and multi line text 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

Regarding the variable “arrOfFieldInternalNamesToSkip”:
The array “arrOfFieldInternalNamesToSkip” is used to prevent the creation of checkboxed for those fields. Add the FieldInternalName of the field(s) you don’t want the checkboxes for.

Regarding the variable “arrDoNotRenderCheckbox” (new in v1.4):
The array “arrDoNotRenderCheckbox” is used for fields that should not render as a checkbox. These fields can be prehidden using the array “arrOfPreHiddenColumns” or passed as an argument in the URL.

Download

The sourcecode for the file “ToggleColumnVisibility.js” and the CEWP is found here

Ask if anything is unclear.

Regards
Alexander

72 thoughts on “Toggle column visibility in list view”

  1. this is great. works much better than what I had. one problem I have, which I see is the same for yours is when exporting to excel.

    Is there a was to hide the same columns when exporting?

    Is there a way to change the checked option using query string var? I think may need another function, but am hoping to see if a way to work it like when the filters are applied then can provide a link the the same hidden fields are hidden.

    Still great work. I have really come to admire your efforts.

    1. Great work.
      No to Q1 make me sad. How about this. I know a datatable or datagrid with the help of code can be exported to Excel. Is there any way to mimic this functionality? A way to copy what is visible then open and paste into Excel?

  2. I am working on the updated query string. I have tested this and it does not appear to be working. I may be missing something so this is what i have tried. I added the qs values after the “?” and no change. I added them as the second parameters after an “&” and no change. I added an alert after this line

    arrOfPreHiddenColumns = arrOfPreHiddenColumns.concat(colFromQueryString.split(','));
    		alert(arrOfPreHiddenColumns)
    

    the alert returns the qs values so it works up to that point.
    The check boxes work perfectly.
    It is only when I try the qs values it does not seem to work.

    I did notice in the alert the values are returned like this:
    value1,value2

    your function is looking for
    [‘value1′,’value2’]
    could this be the issue?

  3. a small help hint. I found that not everyone uses best practices when creating a list, go figure. any way I was having trouble with a large list identifying the attribute name as opposed to the display name. I added a title tag to display “Name” on hover. line 36 added
    title='”+fin+”

    	arrFields.push("<label for='customCheckbox_"+cindex+"' title='"+fin+"'>"+disp+"&nbsp;</label></span>");
    

    now can easily identify names needed for the array.

  4. Great job!
    Thanks a lot, it helped me big time!
    Although I’m having an issue when having multiple listview webparts on a single page.
    It seems to randomly hide other columns from other webparts (sometimes only the headings) or hide them all if they happen to have the same name as the one I really want to hide.
    Is there any easy way that we can specify just the “target” webpart or
    maybe place the ECW on a specific area?
    I would appreciate any help.
    Thanks,

  5. I implemented this script several time with much success. Today I added it to list that is using the Instant List Filter. This adds an additional row for the filter boxes.

    I added some code to your script. really copied what you had and modified it. I added this to the hideColumn(obj) function.

    //header filters
    var VFToToggle = $(".vossers-filterrow >*[class^='vossers'").eq(cindex);
    	if(!toggleCol){
    		VFToToggle.hide();
    	}else{
    		VFToToggle.show();
    	}
    
    

    check and uncheck hides and shows these items perfectly. My problem in on page load. These boxes are just hanging there until I check, unchceck one of the hidden columns.

    How can I hide this on page load like the arr of columns?

    1. Nevermind, again. Actually I did 2 things. Removed the code above caused I realized your already handled that.
      1. I placed the list filter code before the hide columns code.
      2. I wraped the init_checkboxes in a $(document).ready function

      working perfectly now.

      thanks

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

    1. Hi,
      Change Line 38 like this:

      arrFields = "<div style='display:none' id='customToggleColumnCheckbox'>"+arrFields.join('')+"</div>"
      

      You could however change the code to “hard code” the columns to hide, thus eliminating the need for passing the values in the URL.

      Alexander

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

    });

  8. This works great, thanks.

    Can I prevent columns from having the show/hide option completely? I have two columns where I don’t want a show/hide option and don’t want them to display as a choice to hide at all.

  9. Hi, this is really nice..

    Can you please write the same JavaScript to work on data view. also can we do something so that the view item link is clicked also opens the display page with the columns hidden.

    Thank you!

    1. Hi,
      With data view, do you mean a SharePoint Designer created list view?

      If so, it would be very difficult to create something generic because of the fact that the dataview is custom made by each and every user.

      It would be possible to do this, but not in a generic way. I it would have to be a custom made solution.

      Alexander

  10. Hey Alexander, What would be the easiest way to make this script work on a webpart page that has multiple lists /views. I am creating a dashboard that has several views for one list. When I added this script it created a check box for every column in every view on the page, replicating many of them.

    I am also using Christophe’s Easy Tabs. If I can only show this for one view I can get by. Was hoping there is a way to maybe dispaly by a webpart ID and display each the check boxes for each visible view. What do you think, possible, impossible, difficult?

  11. hi Alexander,

    Its my first time to write you but many times i have tried your solutions.

    Alexander, i want to fix the column heading in list but this will not to disturb the group fields. kindly help me out.

    Thanks

  12. i have a list, having more then 15000 list items, data displayed in this in multiple groups, for eg group by month and then zone. i want to fix the column heading of this list just like datasheet view but i dont want to disturb the data grouping.

    i had found a script over the internet for this but this will expand all the groups on loading, because of this all client computers hang for almost 4..5 minutes.

    i want to fix the column heading while scrolling the items but do not want to disturb data groups.

  13. Excellent. you are awesome man ! Now is it possible to check for values that are non blanks in each and just display them – ie.,display only those fields that have values.

    thanks much-

  14. Hi,

    I have a document library with 2 content types 1 is for folder and 1 is the document.
    I have created a view with both display columns came from 2 content types.
    Now my issue is if I am in the folder level the content types folder columns only have values when I click in the folder the document content types column display only.

    now is there a way to do this in jscript? I mean if i am in the folder level It will hide all document content type column? same thing goes when i am inside the folder the folder content types column will hide.

    Please help.

    Thanks!

    1. Hi,
      You could check the URL for the parameter “RootFolder” and have a script hide the columns based upon the value for the parameter.

      Use this code to retrieve it:

      var currFolder = GetUrlKeyValue("RootFolder");
      

      Alexander

  15. Truely a great script. I am having an issue with a list view containg more than 20 columns. This is the only script running on the page, about 150 row items and started woth 50 columns. I would get a Windows IE error “Stop running the script?” Do yu know the max number of columns this supports?

    1. Hi,
      I do not have a number for you, but try reducing the number of rows in the view. This code “times out” due to a large number of instructions when iterating trough all items in a large list view.

      Alexander

  16. I am trying to use this to hide the filtered column in a grouped list view. It works fine, by adding the one column to arrOfPreHiddenColumns and all the remaining to arrOfFieldInternalNamesToSkip.

    Unfortunately it leaves me a check boox with my filtered list column name. If I add my filtered column to arrOfPreHiddenColumns, the column is not hidden.

    Is their a streamilined way to hide a filtered list column in a grouped list view, and not provide a means to unhide it?

  17. Dear Alex,

    I really would like to use this script but it doesn’t work in Sharepoint 2010. Do you have any plan to release the modified version of it for Sharepoint 2010?

    Many Thanks,
    Azita

      1. Hi Alex, I did not think I will get a response, but I did and I so appreciative. I will try the solution and get back to you..
        But please I also need your expertise with SP list form validation. How do I validate for required fields and put the error messages on the top of the form.

        Also I want to be able to allow the text “not available” for my date field if user doesn’t have the registered date at the time of filling the form. Or is how you would suggest this to be done if text/string cannot be entered in the date field
        And if the user has and enters the date, I also what to check that date entered is not greater than today as the registered date cannot be in future

        And lastly I had as yes/no/not available radio button question with sub questions and if uses selects “yes” then sub question are required but if they select ‘no”, I want to populate the sub questions with the value ‘NO” and is they select ‘not available” I want to populate the sub questions with the value “not available” and if the go from ‘no’ or ‘not available’ buttons to ‘yes’ I want to remove the set values.

        Thanks again

      2. Hi, This was a lot in one go… I’m in the process of making a solution for dynamically setting mandatory fields in a NewForm / EditForm. I guess you must wait until that is published and then we can take the rest from there.

        Alexander

    1. Thanks again, i’ll wait. Oh by the way the div.customToggleColumnCheckbox … for the toggle checkbox column did not work as i needed it too.
      i was actually looking to align the checkboxes … something like this .. http://jsfiddle.net/DuSP5/

      Can this be incorporated with you toggle script?
      Many thanks

    2. Hi,
      That should not be a problem, but if you could write that code, you’ll do this with no problems. Look in the file “ToggleColumnVisibility.js” in line 64.

      Alexander

    3. Hi,
      Sorry for the late reply. I’ll make a not of it and see what i can do. I’m a bit short on time these days and cannot promise anything.

      Alexander

    4. Still need help with writting the code that will arranging the checkboxes in a table, i have about 30 columns and would like to have 10checkboxes in a column so its all neat and tidy.
      Any suggestion or help anyone?
      thanks

    5. Hi,
      Sorry I forgot about your request. Here is a little code that you must put BELOW the call to “init_Checkboxes” in your CEWP:

      wrapCheckboxesInTable(5);
      function wrapCheckboxesInTable(breakAfter){
      	var counter = 0;
      	$("div.customToggleColumnCheckbox").prepend("<table id='customToggleColumnTable' cellpadding='0' cellspacing='0'></table>");
      	$("div.customToggleColumnCheckbox").find('input:checkbox').each(function(i,o){		
      		if(i===0 || counter%breakAfter===0){
      			$("#customToggleColumnTable").append("<tr></tr>");
      		}
      		$("#customToggleColumnTable").find('tr:last').append("<td></td>");
      		$(this).parents('span:first').prependTo($("#customToggleColumnTable").find('td:last'));
      		counter += 1;		
      	});
      }
      

      The argument “breakAfter” is the number of columns you want in the table.

      Hope this helps,
      Alexander

  18. Any ideas why I am getting a javascript error:

    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2; MS-RTC LM 8)
    Timestamp: Thu, 5 Jan 2012 18:51:04 UTC

    Message: Object doesn’t support this property or method
    Line: 87
    Char: 3
    Code: 0
    URI: (rest of my url-removed from this post)/ToggleColumnVisibility.js

  19. I am unable to download the ToggleColumnVisibility.js script. Could you please specify if there is another link from where I can download this file.

    thanks

    san

  20. Just what I need.
    NOTES: for Sharepoint 2010 v1.0, I found a small problem with ToggleColumnVisibility.js:

    if(typeof($.fn.jquery).match(‘1.6’)===null)
    should be
    if(($.fn.jquery).match(‘1.6’)===null)

  21. Very useful script, apologise for my ignorance, but is there any way of making default where no checkboxes are selected at start. As I have 20+ columns and finding all the names is tedious!

  22. Great solution! A few questions. I have it working but I have about 200 fields. I don’t intend to make use of all 200 in one list by maybe more like 50.
    1) I’d like to reverse the logic so that all fields are uncheck by default except a small set of exceptions. When the page loads I’ll check the ones I want to add. Can this be easily done?
    2) Any way to have the checkboxes appear in alphabetical order?
    3) I’ve used the added piece that lines up all the checkboxe into nice columns but the text size increased dramatically. Can the text size be set?
    4) When I use this solution in combination with the LimitMultilineTextInView solution the limit solution breaks. Any thoughts?
    Again, very very helpful.
    Thanks,
    Matt

  23. Hi Alex,

    Thank you for the solution, however i could not display checkbox as your screen above. What i did is the following:
    – Create library called scripts containing jquery and
    – Create a blank web part page
    – add content editor webpart in web part page
    – add script into the content query webpart

    what did i missed?. How do script find the list that we want to display?. Thank you

  24. Hi Alex,

    I love this solution and really have a need for it. Will it work in SP 2013? If so, I must be doing something wrong. I paste your CEWP text into a CEWP under my List Webpart and nothing happens. Any help is appreciated.

    Gary

      1. Hi Alex,

        Thank you for the quick response.

        I know that this wasn’t developed for SP 2013, but thought I would ask anyway.

        I, unfortunately, don’t see any errors in developer console. The page loads fine, but there’s no check boxes displayed. 🙁 I could satisfy my requirement with OOTB SP Views, but I can’t figure out a way to switch the Current View of a List WebPart. I’m not even sure if that’s possible.

        Thanks anyway,
        Gary

      2. Hi,
        Sorry, but I haven’t had the time to look at this one. It is most likely an issue with the elements in the page that the script “looks at” to identify the columns and insert the checkboxes.

        If you try to delay the loading of the script to ensure the page has finished loading, and if this does not help, you must try to step trough the script to see if it targets elements that no longer exist in the page (and need to be changed).

        Alexander

Leave a Reply