Accordion in SharePoint form

12.03.2011: I have posted a new release, you find it here.


In this example i will show how to use the jQuery UI widget “Accordion” in a SharePoint form.

NewForm:
IMG
On form validation (refresh) it selects the first section containing empty fields:
IMG
DispForm with attachment:
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

A folder named “jQueryUI” containing the scripts and the “images”-folder for the selected theme:
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

The jQuery UI-library is found here. Find the theme of your choice – mine is “smootness” – and download the files (select the widgets and effects you want – the file is dynamically built according to your selection).

Add a CEWP below your NewForm, DispForm and EditForm.

Add this code:

<DIV id="accordion" style="font-size:14px">	
	<H3><A href="#accordion-0">Section 1</A></H3>
	<div><table width="100%" id="accTable-0"></table> </div>
	<H3><A href="#accordion-1">Section 2</A></H3>
	<div><table width="100%" id="accTable-1"></table> </div>
	<H3><A href="#accordion-2">Section 3</A></H3>
	<div><table width="100%" id="accTable-2"></table> </div>
	<H3><A href="#accordion-3">Attachments</A></H3>
	<div><table width="100%" id="accTable-3"></table> </div>	
</DIV>

<link type="text/css" href="/test/English/Javascript/jQueryUI/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/jQueryUI/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript">

// Array of all fields - format: accID|FieldInternalName
// Note that accID is zero-indexed
arrOfFields = ['0|Title','0|SectionOneText','0|Section1Choice',
		  '1|Responsible','1|Section2Text',
		  '2|Section3Multiline','2|Section3Choice'];

// Initiate all the fields
fields = init_fields();

// Add the "accordion" to the formtable	
$("#accordion").insertAfter('.ms-formtable').accordion({autoHeight: false,animated: false});
// Loop trough all fields and move them to the right accordion section
fValAccID = '';
$.each(arrOfFields,function(idx,item){
	var split = item.split('|');
	var accID = split[0];
	var fieldName = split[1];
	if(fields[fieldName]!=undefined){
		currField = $(fields[fieldName]);
		currField.appendTo('#accTable-'+accID);
		
		// Formvalidation - find the first tab with empty required fields
		if(fValAccID == '' && currField.find('.ms-formbody span.ms-formvalidation').length>0){
			fValAccID = accID;
		}
	}
});

// Move the Attachment's to the last section
$("#idAttachmentsRow").appendTo('#accTable-3');

// Are there any required fields not filled? - select the section containing the first field
if(fValAccID !=''){
	// Show the right section
	setTimeout(function(){$('#accordion').accordion('activate',parseInt(fValAccID));},10);
}

// Fix IE8 issue with content not showing (because it is in a table within the DIV) + remove the default padding
$(".ui-accordion-content").css({'zoom':1,'padding':'0px'});

// function - to make "object" of all tr's in the form
function init_fields(){
  var res = {};
  $("td.ms-formbody").each(function(){
	  if($(this).html().indexOf('FieldInternalName="')<0) return;
	  var start = $(this).html().indexOf('FieldInternalName="')+19;
	  var stopp = $(this).html().indexOf('FieldType="')-7;
	  var nm = $(this).html().substring(start,stopp);
	  res[nm] = this.parentNode;
  });
  return res;
}
</script>

The only parameters you need to edit in the script is the array of FieldInternalNames. The format of the variable “arrOfFields” is accID|FieldInternalName.

In the html above the script, adapt the number’s of sections – and the section’s display name. The accID corresponds with the index of the table to insert the content in (zero-indexed).

All fields must be added to a section – if not it looks ugly….

Note: As for the “Tabs in SharePoint form”, by now i have tested and found that columns of type “Multiple lines of text (Rich text or Enhanced rich text) do not work. What happens is that the section shows some of the fields hidden parts.

I have not done any testing on how to prevent this issue, so feel free to notify me if you find a workaround.

Note: The animation is disabled because of a “flicker problem” in IE8 due to the page being rendered in “Quirks Mode”.

Regards
Alexander

71 Comments on “Accordion in SharePoint form

  1. Hi Alexander,

    How would I accomplish this task in a single item form in SPD. I tried and all I got in the CEWP was headings and no accordions.

    Thanks for all your help

  2. I went in and tried but I am getting nothing. I am using a single item form which just wraps the headings in tags. I went in and switched the to h3 ms.standard headers and opened the form in toolpane view added a CEWP under the form but still nothing.

    Any help will be greatly appreciated. Should I have a different name other than CustomForm when I initiate?

    1. Hi,
      I may have misunderstood how you created your form. Can you explain how you make your “single item form”?.

      I do not modify my forms in SPD as i do all modification with JavaScript…

      Have you got it working in a standard NewForm or EditForm not modified in SPD?

      Alexander

  3. Hi Alex,

    When I use a “New” or “Edit”form and follow your instructions on the site it works great.

    I create a single item form as follow:

    What I do is insert a dataview webpart in SPD . When I do I choose my list from the data soure libray which open the list. The you choose the items from the list you want and select “insert as a “single item form”.

    Thanks for all your help I have been trying to get this to work for a long time.

    1. Hi,
      What you must do is to make your “label-TD’s” recognizable by the function “init_fields_CustomForm()”.

      The custom function below looks for all TD’s in the page that has a class of “ms-formlabel”, and who have a “h3” with class “ms-standardheader” containing the label.

      To adapt the script to your custom form, you must add a class as described above and edit the line “$(“td.ms-formlabel h3.ms-standardheader”).each…” in the script below to match your TD’s class.

      function init_fields_CustomForm(){
        var res = {};
        $("td.ms-formlabel h3.ms-standardheader").each(function(){
        var str = $.trim($(this).text().replace(/*/g,''));
      	  res[str] = $(this).parents('tr:first');
        });
        return res;
      }
      

      Alexander

  4. wow ok, what about date field? for some reason date filed shows up but barely readable…..

    Does the tab control have the same problem with multiline?

    1. The tabs script has the same issues with the multi line text fields (rich and enhanced), but the date field issue is fixed. Look at the code and copy the style section at the top. I have not had the time to update this article…

      Alexander

  5. Hi Alex

    Quick questionI hope 🙂

    Is there a way to not place some fields inside the accordion and have them appear at the bottom not the top of the page

    That would look rather nice not ugly I would think and that would let me use enhanced multiline text boxes

    Do you understand question?

    Because multiline plain text is rather lame….

    Tony

    Tony

  6. Hi Alex

    Me again, is there anyway to collapse all of the sections, the insert before works beautifully just need to have all of them collapsed

    Tony

  7. $(“#accordion”).insertBefore(‘.ms-formtable’).accordion({autoHeight: false,animated: false,collapsible: true});

    Thayt permits me to close everything after the fact how do I start that way 🙂

  8. Hi Genius,

    I need an accordion in SharePoint List, to show a list with many columns in an accordion, with Primary Details on First Tab, Secondary Details on Second Tab and so on ……… maybe by using various Views on each tab…

    Kindly guide me … Expecting your reply urgently…
    Thank you in advance…

    Regards,
    Thendral

  9. Hi, a quick quest (hope so) if I don’t want the last section (attachements), it´s seems that is not enough to out comment the $(“#idAttachmentsRow”).appendTo(‘#accTable-3’); – so is this doable in some other way?

  10. Alexander,
    Can you provide more detail for the specific folders/files that need to be downloaded from the jquery and jqueryui sites and also more detail regarding the sharepoint library setup; you mentioned creating a folder in the library named jQueryUI. The download from jqueryui site results in 3 folders (CSS, development-bundle, js) and an index.html file. Is it necessary to upload the entire jqueryui download to the sharepoint library (for example, is it necessary to upload the development-bundle folder)? The image you have above shows just 2 files (jquery-ui-1.7.2.custom and jquery-ui-1.7.2.custom.min) and an images folder (but there is a lot more in the jqueryui download). Lastly, under the terms of the license, can a business use material downloaded from jquery and jqueryui in there corporate sharepoint environment? Thanks very much for your help.
    Steve

    1. Hi,
      From jquery.com you download the latest version. From jqueryui.com you download the latest build 1.8. This download also contains the latest bulid of jquery (1.4.2).

      As you noticed, only the files “jquery-ui-1.8.custom.min.js” from the “js” folder, and the “jquery-ui-1.8.custom.css” and the “images” folder from the “css” folder is needed.

      The license can be found here

      You don’t have to do anything special to choose one license or the other and you don’t have to notify anyone which license you are using. You are free to use a jQuery project in commercial projects as long as the copyright header is left intact.

      Alexander

  11. Alexander,
    Are the jQuery UI-library files (jquery-ui-1.7.2.custom and jquery-ui-1.7.2.custom.min) needed for Accordion to work? Why does the code that goes into the CEWP only reference the jquery-ui-1.7.2.custom.min file and not the jquery-ui-1.7.2.custom file?
    Thanks,
    Steve

  12. Hi Alexander,
    Is it necessary to keep the code you’ve provided in a CEWP? Would it make a difference if I launched Designer and added your code directly to the NewForm.aspx page immediately following the DataFormWebPart for the List? Would your code still work or is this just not possible and if it is possible would your code work as is or would it require modifications. I know the trick to add a CEWP to a form like NewForm.aspx (in the URL replace everything following the ? with ToolPaneView=2) but one of my clients has a situation where the NewForm.aspx simply cannot accommodate a CEWP which is why I’m interested in knowing this. Many thanks.
    Steve

  13. Alexander,
    As you said, it doesn’t matter if you use the CEWP or not. But weather I use the CEWP or put the code directly into the page using Designer, the results are the same. The Accordion doesn’t error but it doesn’t work either. What happens is that when the page is displayed in the browser, the form itself (fields and all) look fine, as they normally do (but no Accordion). However, the 4 section labels, that is, the words themselves: Section 1, Section 2, Section 3, and Attachments are displayed below the form. I know I’m doing it correctly because testing at home, it works, but testing at the office, it doesn’t. I was wondering if you had any ideas about why the behaviour I’m describing might occur Thanks.
    Steve

  14. Hi there – this works fab apart from with fields that have a space in them, or a slash.

    For example, one field is called “Start Time”, and i put ‘0|Start Time’ in the arrOfFields but it doesn’t work, that field stays at the top of the form along with all the other fields with spaces in the name. Also, i have a field called “Hotel/Venue”… how would I do the “/” in the arrOfFields declaration?

    Fab solution so very well done and thank you, can’t wait to see all my fields in the groups! 🙂

  15. Hi,

    I have 2 questions.

    1st
    How would i change the display name of a field using the accordion.
    2nd
    Is it possible to have a formated form with the accordion.

    1. Hi,
      Changing the display name can be done like this (requires the function init_fields):

      $(fields['Title']).find('.ms-formlabel h3').text('My new title');
      

      Q2 you must specify some more for me to understand what you want to do.

      Alexander

    2. Here is the init_fields function in the accordion code. If I insert the code to rename a field, the field is not renamed and the accordion isn’t functioning anymore.

      any idea?

      function init_fields(){
                
      	  var res = {};
      	  $("td.ms-formbody").each(function(){
      	      if($(this).html().indexOf('FieldInternalName="')<0) return;
      	      var start = $(this).html().indexOf('FieldInternalName="')+19;
      	      var stopp = $(this).html().indexOf('FieldType="')-7;
      	      var nm = $(this).html().substring(start,stopp);
      	      res[nm] = this.parentNode;
      	  });
      	  return res;
      	}
      
      
      
    3. HI,
      I’m not sure what you mean.

      If you drop this code:

      $(fields['Title']).find('.ms-formlabel h3').text('My new title');
      

      in line 25 in the code above, it renames the Title field “My new title”.

      Please clarify.

      Alexander

  16. Hi Alexander,

    Thanks for the good post. I have one doubt. If My column name is having white spaces then I’m unable to show that column in the Accordion. Could u please tell me how to access Column Names which is having white spaces in it.
    Thanks,
    Rao.

    1. I got the answer for this question. But I’m having another problem that, if a perticular column is having more than one space charecter it is not accepting (i.e., Continuously learn and adapt). The word contains 3 spaces.

      could u plz solve my problem….

      Thanks,
      Rao.

    2. Thanks Alexander,

      I got it from ur valuble suggestion. But one more thing, Accordion is possible for Custom List Forms?

      Thanks,
      Rao.

  17. Hi Alexander…script works great however my date field (next to the date picker) has been reduced in size to illegible. Thoughts for a fix?

    1. Look at the previous article (Tabs in SharePoint form). There i have added this style tag in the CEWP code:

      <!-- Date field text size -->
      <style type="text/css">
      .ms-dtinput,.ms-dttimeinput{
      	font-size:0.7em;
      }
      </style>
      

      Alexander

  18. Hey Alexander,

    I’m having a problem with this script. I have changed the path of Jquery-UI-Custom (JS) and the CSS files to an “internal” list.

    So far what i’ve changed is :

    The files were correctly uploaded, the UI file contains all features, and there are no mistakes in typing (I changed both files names and made them more simple to make sure of that)

    Anyway, this is what’s going on:

    http://image.gxzone.com/images/a/3/a34f9401532.jpg

    Any ideas? I would really appreciate some help.

    Thanks,
    Osvaldo

  19. I could make it work after some coding … I don’t know what was wrong but I was able to make it work. Thanks for your answer anyway.

    Now I’d like to ask you something else, if you don’t mind!

    I’m working with content types, and some of this “sections” do not apply to all of them. The only thing that came up to my mind was to “IF” the sections’ code depending on the content type or some parameter in the URL.

    I could make it work if this sections were only made using javascript, but there is also some HTML (am I right?) in the beginning, and I can’t figure out how to put that inside a conditional frame.

    Hope you can help me, and thanks for your time again 🙂

    1. Hi,
      Modify the code like this (only part of the code is provided here):

      <DIV id="accordion" style="font-size:14px"></DIV>
      
      <link type="text/css" href="/test/English/Javascript/jQueryUI/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/jQueryUI/jquery-ui-1.7.2.custom.min.js"></script>
      <script type="text/javascript">
      
      var myHtmlBuffer = [];
      	myHtmlBuffer.push("<H3><A href='#accordion-0'>Section 1</A></H3>");
      	myHtmlBuffer.push("<div><table width='100%' id='accTable-0'></table> </div>");
      	myHtmlBuffer.push("<H3><A href='#accordion-1'>Section 2</A></H3>");
      	myHtmlBuffer.push("<div><table width='100%' id='accTable-1'></table> </div>");
      	myHtmlBuffer.push("<H3><A href='#accordion-2'>Section 3</A></H3>");
      	myHtmlBuffer.push("<div><table width='100%' id='accTable-2'></table> </div>");
      	myHtmlBuffer.push("<H3><A href='#accordion-3'>Attachments</A></H3>");
      	myHtmlBuffer.push("<div><table width='100%' id='accTable-3'></table> </div>");	
      	var myHtml = myHtmlBuffer.join('');
      $("#accordion").html(myHtml);
      

      This code “moves” the html into the javascript and lets you “if” it.

      Alexander

  20. Hi Alex, i have a little problem here with a application that i included this solution. I have a drop down with more than 20 elements, when the user select this control, the render of the control is not in the correct place. The render is far, far away of the original control.
    Do you have this problem? How can i resolve that?
    Thanks a lot.

    Sebastián.-

  21. In your script, we are working with the fieldinternal name. Is it possible to use the fieldinternal name but rename the column in the form without creating a custom newform?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.