Category Archives: Javascript

Arrange multiple selection lookup vertically

08.12.2009 Small update to fix scroll vertically.

Here’s a tip on how to rearrange the multiple select lookup column in a vertical orientation.

This is the default orientation:
IMG

This is the new vertical orientation:
IMG

Here’s how its done


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.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

Add a CEWP below your list-form like this:IMG

And add this code:

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Call script
mulitiLookupVertical('MultiLookup');

function mulitiLookupVertical(FieldInternalName,width){
if(width==undefined)width=370;
var thisField = $(fields[FieldInternalName]);
	thisField.find("td.ms-formbody td").each(function(){
		// Wrap in tr's and set width
		$(this).wrap("<tr></tr>")
			.find('div')
			.css({'width':width});

	});
	// Buttons
	thisField.find('br').replaceWith(' ');
	thisField.find('button:first').text('Add');
	thisField.find('button:last').text('Remove');	
}

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>

Ragards
Alexander

Edit the title property of a field to add custom tooltip

29.10.2009 Update: I have written a new article on how to add HTML-style tool tip – read it here.


I got a request for a method of adding a custom mouse-over tool tip on a field in a SharePoint form. Here is a quick example.

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.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

Add a CEWP below your list-form like this:IMG

And add this code:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
fields = init_fields();

$(fields['Title']).find('input').attr('title','This is a new mouse-over tooltip');

function init_fields(){
  var res = {};
  $(&quot;td.ms-formbody&quot;).each(function(){
	  if($(this).html().indexOf('FieldInternalName=&quot;')&lt;0) return;	
	  var start = $(this).html().indexOf('FieldInternalName=&quot;')+19;
	  var stopp = $(this).html().indexOf('FieldType=&quot;')-7; 
	  var nm = $(this).html().substring(start,stopp);
	  res[nm] = this.parentNode;
  });
  return res;
}
&lt;/script&gt;

The tooltip should look like this:
IMG

Ask if this example is not enough.

Alexander

Master document template library

Have you ever wanted to:

  • have multiple document templates in i one document library
    – without having to use content types?
  • use the same template in multiple document library’s?
  • have different document templates available in each view?
  • have easy access to editing the templates?

I will provide a javascript solution that uses a standard document library as a master template placeholder. This library can have an unlimited number of templates and each template can be used in multiple document libraries. On each template you can specify which document library to use it in, and whether to use the template in all views, or to specify which views to use it in.

Then, in the document library where you want to use these templates, just drop a CEWP with some script references and like magic – your templates appear. No need to hand code each menu item – they are pulled straight from your master template library based on your metadata on each template.

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.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

The scripts “interaction.js” and “stringBuffer.js” is created by Erucy and published on CodePlex.

The sourcecode for “MasterDocumentTemplates.js” is provided below.

Create your master template placeholder library like this:

Create a standard document library and add two columns:
UsedIn of type “Multiple lines of text”

Here the document library’s where the template will be accessible is specified like this:
– DisplayNameOfYourLibrary|viewNameFromURL;
– You can add multiple libraries and multiple views for each library – separated by “|” for each view, and “;” for each library.

MouseOver of type “Single line of text”.

Here the description (in “bigIcon-mode”) or MouseOver (in “smallIcon-mode”) on the template in the dropdown is set.

The columns in the template library looks like this:
IMG

And the template library look like this with a few templates added:
IMG

As you see from the screenshot – all templates is used in the document library named “MyDocumentLibrary”. The file “PowerPoint template” is visible only in the view “PowerPoint” in “MyDocumentLibrary”. The rest of the templates is visible in all views.

Here is the code for the file “MasterDocumentTemplates.js”:

/* Add dropdown menu in document library - pulls templates from master template library and points &quot;save&quot; to the current library
 * Requires a &quot;Templates&quot; document library with the following fields (FieldInternalName):
 * &quot;UsedIn&quot;
 * - Multiple line of plain text. Here the document library's where the template will be accessible is specified like this:
 *   DisplayNameOfYourLibrary|viewNameFromURL;
 *   You can add multiple libraries and multiple views for each library - separated by &quot;|&quot; for each view, and &quot;;&quot; for each library. 
 *   If you do not specify view - the template is accessible to all views that have this script referred.
 * &quot;MouseOver&quot;
 * - Description (in &quot;bigIcon-mode&quot;) or MouseOver (in &quot;smallIcon-mode&quot;) on the template in the dropdown
 *
 * -----------------------------
 * Author: Alexander Bautz
 * Version: 1.2
 * LastMod: 18.10.2009
 * -----------------------------
 * Must include reference to jQuery and to the folloving scripts (http://spjslib.codeplex.com):
 * ----------------------------------------------------
 * interaction.js
 * stringBuffer.js
 * ----------------------------------------------------
Ex:
getTemplatesForThisLibrary('DocumentTemplates','/test/English','',true,true,'Upload document','Select template from list');

Parameters explained:
* templatesListName:
  Document library DisplayName of your master template library
* templatesListbaseUrl:
  The baseUrl of the site the library resides in (not the URL to the Document library it selves)
* targetListUrlDir:
 The actual URL path to the save location - to save in &quot;current&quot; library - where the menu is - use ''
* bigIcon:
 true for large icon and description (from field &quot;MouseOver&quot;) below the template name
 false for small icon mode with the value from the field &quot;MouseOver&quot; as tooltip and only the template name visible
* uploadOption:
 true add option for upload
 false hides option for upload
* uploadButtonTitle:
 if uploadOption set to true - the text displayed on the upload &quot;option&quot;&lt;/li&gt;
* menuTitle:
 The text on the dropdown-menu
*/

function getTemplatesForThisLibrary(templatesListName,templatesListbaseUrl,targetListUrlDir,bigIcon,uploadOption,uploadButtonTitle,menuTitle){
var bgColor = $('.ms-quicklaunchheader').css('background-color');
var btnBgColor = $('.ms-viewselector').css('background-color');
var thisViewNameRaw = $(&quot;#aspnetForm&quot;).attr('action');
var thisViewName = thisViewNameRaw.substring(0,thisViewNameRaw.indexOf('.aspx'));

wsBaseUrl = templatesListbaseUrl + '/_vti_bin/'; 
var q = &quot;&lt;Where&gt;&lt;Contains&gt;&lt;FieldRef Name='UsedIn'/&gt;&lt;Value Type='Text'&gt;&quot; + ctx.ListTitle + &quot;&lt;/Value&gt;&lt;/Contains&gt;&lt;/Where&gt;&quot; +
		&quot;&lt;OrderBy&gt;&lt;FieldRef Name='FileLeafRef' Ascending='True'/&gt;&lt;/OrderBy&gt;&quot;;
var links = '';
if(bigIcon){
	var iconPrefix = 'lg_';
	var menuClass = 'ms-MenuUILarge';
	var uploadIMG = 'menuuploaddocument.gif';
}else{
	var iconPrefix = '';
	var menuClass = 'ms-MenuUI';
	var uploadIMG = 'doclink.gif';
}

var res = queryItems(templatesListName,q,['UsedIn','FileLeafRef','MouseOver','DocIcon'],25);
	if(res.count&gt;0){
		if(targetListUrlDir==''){
			var listURLRaw = ctx.listUrlDir;
			var listUrl = listURLRaw.substring(listURLRaw.lastIndexOf('/'));
		}else{
			listUrl = &quot;/&quot; + targetListUrlDir;
		}
	    $.each(res.items, function(idx, item){ 
	    var showInView = false;
	    // Split the UsedIn value to separate the document library names
	    var useInSplit = item['UsedIn'].split(';');
	        for(i=0;i&lt;useInSplit.length;i++){ 
	        	// Split the value to find the view's in which to show the template
	       		var usedInSplitAgain = useInSplit[i].split('|');	       		
	       		if(usedInSplitAgain.length&gt;1){ // If length &gt; 1 there is specified one or more views
		       		if(usedInSplitAgain[0]==ctx.ListTitle){
				        for(j=1;j&lt;usedInSplitAgain.length;j++){
			        		if(usedInSplitAgain[j].toLowerCase()==thisViewName.toLowerCase()){
				        		// Show in this view
				        		showInView = true;
				        	}
				        }
					}				
				}else{ // View not specified - show in all views
					if(usedInSplitAgain[0]==ctx.ListTitle){
						showInView = true;
					}
				}
	        }
	        
			if(showInView){
		        var DocIcon = item['DocIcon'];
		        var docName = item['FileLeafRef'].substring(item['FileLeafRef'].indexOf(';#')+2);
		        var docDescription = '';
		        var mouseOver = '';		        
		        if(item['MouseOver']!=null){
		        	var docDescription = &quot;&lt;font color='#696969'&gt;&quot; + item['MouseOver'] + &quot;&lt;/font&gt;&quot;;
			        	if(!bigIcon){
			        		var mouseOver = item['MouseOver'];
			        	}
		        }	        
		        var link = &quot;createNewDocumentWithProgID('&quot; + ctx.HttpRoot + &quot;/&quot; + templatesListName + &quot;/&quot; + docName + &quot;','&quot; + ctx.HttpRoot + listUrl + &quot;','SharePoint.OpenDocuments', false)&quot;;
				if(bigIcon){
					 links += &quot;&lt;table style='border:1px white' width='100%' cellpadding='2' cellspacing='0' &quot; +
					 &quot;class='templateMenuHover &quot; + menuClass + &quot;' &quot; +
	        		 &quot;title='&quot; + mouseOver + &quot;' onclick=&quot;javascript:hideMenu($(this));&quot; + link + &quot;&quot;&gt;&quot; +
	        		 &quot;&lt;tr&gt;&lt;td style='vertical-align:middle'&gt;&lt;img style='text-align:center;vertical-align:middle' src='/_layouts/images/&quot; + iconPrefix + &quot;ic&quot; + DocIcon + &quot;.gif' /&gt;&lt;/td&gt;&quot; +
	        		 &quot;&lt;td width='100%' style='padding:0 15 0 10'&gt;&lt;b&gt;&quot; + docName + &quot;&lt;/b&gt;&lt;br&gt;&quot; + docDescription + &quot;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&quot;;	        		 
				}else{
					 links += &quot;&lt;table style='border:1px white' width='100%' cellpadding='2' cellspacing='0' &quot; +
					 &quot;class='templateMenuHover &quot; + menuClass + &quot;' &quot; +
	        		 &quot;title='&quot; + mouseOver + &quot;' onclick=&quot;javascript:hideMenu($(this));&quot; + link + &quot;&quot;&gt;&quot; + 
	        		 &quot;&lt;tr&gt;&lt;td style='vertical-align:middle;padding-left:2px'&gt;&lt;img src='/_layouts/images/&quot; + iconPrefix + &quot;ic&quot; + DocIcon + &quot;.gif' /&gt;&lt;/td&gt;&quot; + 
	        		 &quot;&lt;td width='100%' style='padding:0 15 0 10;white-space:nowrap'&gt;&quot; + docName + &quot;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&quot;;
				}
	    	}
	    }); 
    }else{ 
    	// No templates available for this view
		 links += &quot;&lt;table style='border:1px white' width='100%' cellpadding='2' cellspacing='0' &quot; +
		 &quot;class='templateMenuHover &quot; + menuClass + &quot;' &quot; + &quot;title=''&gt;&quot; + 
		 &quot;&lt;tr&gt;&lt;td style='vertical-align:middle;padding-left:2px'&gt;&lt;img src='/_layouts/images/&quot; + iconPrefix + &quot;ichlp.gif' /&gt;&lt;/td&gt;&quot; + 
		 &quot;&lt;td width='100%' style='white-space:nowrap;padding:0 10 0 10'&gt;No templates available&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&quot;;
   	
    }
    // Show upload option
    if(uploadOption){
		 links += &quot;&lt;table style='border:1px white' width='100%' cellpadding='2' cellspacing='0' &quot; +
		 &quot;class='templateMenuHover &quot; + menuClass + &quot;' &quot; + &quot;title='' onclick='location.href=&quot;&quot; + ctx.HttpRoot + &quot;/_layouts/Upload.aspx?List=&quot; + ctx.listName + &quot;&quot;'&gt;&quot; + 
		 &quot;&lt;tr&gt;&lt;td style='vertical-align:middle;padding-left:2px'&gt;&lt;img src='/_layouts/images/&quot; + uploadIMG +&quot;' /&gt;&lt;/td&gt;&quot; + 
		 &quot;&lt;td width='100%' style='white-space:nowrap;padding:0 10 0 10'&gt;&quot; + uploadButtonTitle + &quot;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&quot;;    			 
    }
    // Build the menu
  	links = &quot;&lt;div style='border-top:thin groove white;border-bottom:thin groove white;border-left:thin groove white;background-color:&quot; + bgColor + &quot;;height:25' &gt;&quot; +
  			&quot;&lt;div style='cursor:pointer;float:left;border:thin groove silver;padding:2;background-color:&quot; + btnBgColor + &quot;' class='templateMenuFirst'&gt;&quot; +
  			&quot;&lt;div title='Open Menu'&gt;&quot; + menuTitle + &quot;&lt;img alt='' src='/_layouts/images/menudark.gif'/&gt;&lt;/div&gt;&quot; +
  			&quot;&lt;div class='templateMenu ms-MenuUIPopupBody' style='display:none'&gt;&quot; + links + &quot;&lt;/div&gt;&quot; +
  			&quot;&lt;/div&gt;&quot; +
  			&quot;&lt;/div&gt;&quot;;
    
    // Insert the menu
	$(&quot;.ms-bodyareaframe&quot;).prepend(links);
	// Add show-hide functionality to the menu
	addShowHideToCustomMenu();
}

function addShowHideToCustomMenu(){ 
	// Add onclick and mouseleave to show and hide the menu
	$('.templateMenuFirst').click(function(){
		$('.templateMenu').slideDown(250)
		.css('position','absolute')
		.css('zIndex','1000')
	})
	.mouseleave(function(){
		$('.templateMenu').fadeOut(350);
	});
	
	// Add hover effect to highlight the element hovered with the mouse
	$(&quot;.templateMenuHover&quot;).hover(
	function () {
		$(this).addClass('ms-MenuUIItemTableHover');
	}, 
	function () {
		$(this).removeClass('ms-MenuUIItemTableHover');
	});
}

function hideMenu(obj){
	// Remove rather than hide to prevent flicker
	$('.templateMenu').remove();
	// Reload page - needed for Firefox
	history.go(0);
}

// Overcome the zIndex glitch in IE7 - http://www.vancelucas.com
$(function() { 
	var zIndexNumber = 1000;
	$('div.templateMenu').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
});

Save this as a file named “MasterDocumentTemplates.js” – be sure to use the right file extension, and upload to the javascript library as shown above.

Then add a CEWP below the list view in the document library where you want the menu to appear.
IMG

And add this code to it:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/interaction.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/stringBuffer.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/MasterDocumentTemplates.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
// bigIcon mode true
getTemplatesForThisLibrary('DocumentTemplates','/test/English','',true,true,'Upload document','Select template from list');
&lt;/script&gt;

Parameters explained:

  • templatesListName
    Document library DisplayName of your master template library
  • templatesListbaseUrl
    The baseUrl of the site the library resides in (not the URL to the Document library it selves)
  • targetListUrlDir
    The actual URL path to the save location – to save in “current” library – where the menu is – use ”
  • bigIcon
    true for large icon and description (from field “MouseOver”) below the template name
    false for small icon mode with the value from the field “MouseOver” as tooltip and only the template name visible
  • uploadOption
    true add option for upload
    false hides option for upload
  • uploadButtonTitle
    if uploadOption set to true – the text displayed on the upload “option”
  • menuTitle
    The text on the dropdown-menu

The menu will appear like this:
IMG
You can edit the color of the “button” and its background “banner” in line 44-45 in the script.

The menu should look like this in the “Default view” (note that the PowerPoint template is not displayed:
IMG

And like this in the view “PowerPoint”:
IMG

If you select “bigIcon=false” the menu looks like this:
IMG

I hope someone finds this “feature” handy!
Ask if something is unclear.

Regards
Alexander

Reformat URL from calculated column with decent clickable link text

19.11.2009 Fixed the bugs from yesterday…
18.11.2009 Added support for grouped views.
17.11.2009 Updated code to remove the filter in the viewheader for the field with the calculated column “Link”. Noted by Paulo Sousa in the post comments. I have also added a code to use for the DispForm to format the link.

If you create a link from a calculated column it is not formatted right in the list view. Here it a small jQuery script to fix this issue.

The list has these columns:
IMG

The code in the calculated column “Link” looks like this:

=&quot;&lt;a title='The mouseover text goes here' href='&quot;&amp;URL&amp;&quot;'&gt;&quot;&amp;Description&amp;&quot;&lt;/a&gt;&quot;

The NewForm looks like this:
IMG

The list view looks like this before the script is added:
IMG

And like this after the script is added:
IMG

How is it done?

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.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

Add a CEWP below the list view like this:
IMG

With this code:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
// Updated 19.11.2009
// Reformat the url in the calculated column
reformatCalculatedColumnUrl();

function reformatCalculatedColumnUrl(){
	$(&quot;.ms-listviewtable td.ms-vb2:contains('href')&quot;).each(function(){
		$(this).html($(this).text())
	});
}

// If grouped by the calculated column - reformat the group header
var groupHeaderClickableLink = true; // Set to false to remove the link on the groupheader
$(&quot;.ms-listviewtable td[class^='ms-gb']&quot;).each(function(){
	if($(this).html().indexOf('&amp;lt;')&gt;0){
		// Get full HTML of group header
		var rawHTML = $(this).html();
		// Extract the part before the calculated column's content
		var preWrap = rawHTML.substring(0,rawHTML.indexOf(&quot;&amp;lt;&quot;));
		// Extract the part after the calculated column's content
		var postWrap = rawHTML.substring(rawHTML.lastIndexOf('&amp;gt;')+4);
	
		if(!groupHeaderClickableLink){
			// Find the clickable part of the calculated column's content 
			var linkTextStart = rawHTML.indexOf('&amp;gt;') + 4;
			var linkTextStop = rawHTML.lastIndexOf('&amp;lt;');
			var linkText = rawHTML.substring(linkTextStart,linkTextStop);
			// Write back the HTML
			$(this).html(preWrap + linkText + postWrap);
		}else{
			// Find the clickable part of the calculated column's content 
			var linkStart = rawHTML.indexOf('&amp;lt;');
			var linkStop = rawHTML.lastIndexOf('&amp;gt;') + 4;
			// Find raw link				
			var rawLink = rawHTML.substring(linkStart,linkStop);
			// Find the parts to keep
			var pre = rawLink.substring(0,rawLink.indexOf('href=') + 6);
			var mid = rawLink.substring(rawLink.lastIndexOf('href=')+6,rawLink.indexOf('&gt;')-1);
			var post = rawLink.substring(rawLink.indexOf('&amp;gt;')-1);
			// Get the full url and replace the &amp;lt; and &amp;gt;
			var fullUrl = (pre + mid + post).replace(/&amp;lt;/g,'&lt;').replace(/&amp;gt;/g,'&gt;');
			// Write back the HTML
			$(this).html(preWrap + fullUrl + postWrap);	
		}
	}
});

// Disable the filter for the field named &quot;Link&quot;
$(&quot;.ms-viewheadertr table[displayname='Link']&quot;).parents('th:first').removeClass('ms-vh2').addClass('ms-vh2-nograd').html(&quot;Link&quot;);

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

The “group by calculated column – feature” is requested by Paulo Sousa. You can specify whether to have a clickable link or a plain text in the group header by setting the parameter “groupHeaderClickableLink” in line 14 to true or false.

In line 50 in this codeblock i have disabled the filter link in the view header for the field with DisplayName “Link” – you must insert your own field’s DisplayName here.

I do not know of a way to “reformat” the filter values for a calculated column, and therefore the filter values will be like the calculated column’s raw value – therefore i found that disabling the filter was he best option.

For use with DispForm – add code to CEWP below list form (edit the location of jquery as needed):

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
fields = init_fields();

// This is an array of FieldInternalNames for all fields to reformat
var arrOfFieldsToReformat = ['Link'];
// Loop trough all fields in array and reformat to decent link
$.each(arrOfFieldsToReformat,function(idx,item){
	var LinkField = $(fields[item]).find('.ms-formbody');
	LinkField.html(LinkField.text());
});

function init_fields(){
var res = {};
$(&quot;td.ms-formbody&quot;).each(function(){
if($(this).html().indexOf('FieldInternalName=&quot;')&lt;0) return; 
var start = $(this).html().indexOf('FieldInternalName=&quot;')+19;
var stopp = $(this).html().indexOf('FieldType=&quot;')-7; 
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
&lt;/script&gt;

In line 6 you must insert your own FieldInternalNames!
You can add multiple FieldInternalNames, comma separated.

This will result in a DispForm like this:
IMG

That’s it!

Regards
Alexander

Hide empty rows in DispForm

17.06.2010 Updated code to support this heading script: Headings in SharePoint Forms – jQuery

Have you ever wanted to hide rows from your DispForm if they are empty?

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.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

To begin with NewForm looks like this:
IMG

And your DispForm like this:
IMG

Add a CEWP below your DispForm list-form like this:
IMG

With this code:

$("td.ms-formbody").each(function(){
// Trim off all white spaces
var val = $(this).text().replace(/\s|xA0/g,'');
// Check the string length - if it's 0 hide the field
	// If it is not a heading - hide it
	if($(this).parents().html().match('FieldName="#H#')==null){
		if(val.length==0){
			$(this).parents('tr:first').hide();
		}
	}
});

Now your DispForm should look like this:
IMG

If you want to hide the table row based on other criteria, adapt the check in line 7 to fit your need – either it’s by length or it’s by string comparison.

Regards
Alexander

Accumulate selections from dropdown to mulitline textfield

19.02.2010: Updated the post with a code example for setting this drop downs as required (requested by Larry). You find the code at the bottom of the article.

28.12.2009: Updated to add support for an optional delimiter character. I have also updated the functionality so that the selection now is moved from the drop down to the “Accumulated selection” when selected (and back when removed from the selection).


This article demonstrates a solution for accumulating single choice selections from a drop down to a hidden multi-line text-field.

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.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

The sourcecode for the file “AccumulateSelectionsToMultilineText.js” is found below.

Add the columns to your list like the picture below. I have two Choice columns with some random choices and a multi-line plain text column to accumulate the selections in.

NOTE:
The default selection must be blank to be able to select the “first value” and accumulate it as the function triggers on change event on the Choice columns.

Add a CEWP below your NewForm list-form (and EditForm if you like) like this:
IMG

With this code:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/AccumulateSelectionsToMultilineText.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
// Array of fields to accumulate values from - format: FieldInternalName of select [delimiter] FieldInternalName of hidden accumulation field
arrFieldsToAccumulate = ['Choice|ChoiceAccumulated','Choice2|Choice2Accumulated'];
// Call function to iterate trough all constellations of fields and hidden accumulator-fields in array defined above
// The function &quot;addAccumulateFunctionOnLoad&quot; now takes one argument: sepChar. This is the  optional delimiter character to separate the selected values
addAccumulateFunctionOnLoad(';');
&lt;/script&gt;

Your NewForm should now look like this:
IMG
Note: The 28.12.2009-update now moves the selection from the dropdown and to the “Accumulated selections”.

And your list view should look like this:
IMG

Some info:

  • The selected values are stored in custom div’s and added to the hidden multi-line text-field when clicking the “OK” button
  • The delimiter in the multi-line text-field is “n”, and the choices therefore is rendered in separate lines in the list-view and in DispForm.aspx
  • The code handles page reload due to form validation and “preserves” the values (it reads them back from the hidden field and rewrites the custom div’s)
  • Note that the actual selection-dropdown is cleared upon form submission
  • When in NewForm or EditForm, a click on one of the accumulated selected values removes the selected element

Sourcecode for the file “AccumulateSelectionsToMultilineText.js”:

/* Accumulate selections from dropdown to multi-line text-column
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * LastMod: 26.12.2009
 * ---------------------------------------------
 * Must include reference to jQuery
 * ---------------------------------------------
 *
 * Call from CEWP BELOW the list form in NewForm.aspx or EditForm.aspx with the code provided in the blog post.
*/
fields = init_fields();

function addAccumulateFunctionOnLoad(sepChar){
if(typeof(sepChar)=='undefined'){
	separatorChar = '';
}else{
	separatorChar = sepChar;
}

	$.each(arrFieldsToAccumulate, function(idx,item){
		var split = item.split('|');
		var from = split[0];
		var to = split[1];
		accumulateOnSelect(from,to);
	});
}

function accumulateOnSelect(fieldFrom,fieldTo){
	// Hide the &quot;hidden&quot; accumulation-input
	$(fields[fieldTo]).hide();
	// Add onchange on select
	$(fields[fieldFrom]).find('select').change(function(){
		if($(this).find('option:selected').val()!=''){		
			appendValuesFromSelect(fieldFrom);
		}
	});
	
	var selectFromTd = $(fields[fieldFrom]).find('.ms-formbody');
		selectFromTd.append(&quot;&lt;span&gt;Accumulated selections:&lt;/span&gt;&quot;);
	var currentSelections = $(fields[fieldTo]).find(':input').val().split(&quot;n&quot;);
	$.each(currentSelections,function(idx,itemValue){
		if(itemValue!=''){
			var newSel = customAddSelection(fieldFrom,itemValue);			
			// Append new selection
			selectFromTd.append(newSel);
		}	
		// Remove the selected value from the drop down					  	
		selectFromTd.find('select option').each(function(){
			if(itemValue!=''){
				var iVal = handleSeparatorChar(itemValue,true);
				if($(this).val()==iVal){
					$(this).remove();
				}
			}
		});
	});	
addCustomClassAttr(fieldFrom);
}

function appendValuesFromSelect(fieldFrom){
	var selectFromTd = $(fields[fieldFrom]).find('.ms-formbody');
	var selectedOpt = selectFromTd.find('select option:selected');
	var selectedvalue = selectedOpt.val();
	if(selectedvalue!=''){
		var newSel = customAddSelection(fieldFrom,selectedvalue);
		// Append new selection
		selectFromTd.append(newSel);	
		// Remove the selected value from the drop down		  	
		selectedOpt.remove();
		// Add hover effect
		addCustomClassAttr(fieldFrom);
	}
}

function customAddSelection(fField,sValue){
sValue = handleSeparatorChar(sValue,false);
var newDiv = $(&quot;&lt;div title='Click to remove from selection' &quot; +
				&quot;class='dummyClass_&quot; + fField + &quot;' &quot; +
				&quot;style='cursor:pointer;padding-left:4px'&gt;&quot; + sValue + &quot;&lt;/div&gt;&quot;);
// Add one time onclick even
newDiv.one(&quot;click&quot;,function(){removeSelectedDiv($(this))});
return newDiv;
}

function addCustomClassAttr(fieldFrom){
	$(&quot;.dummyClass_&quot; + fieldFrom).hover(function(){
		$(this).addClass(&quot;ms-alternating&quot;);						
	},
	function(){
		$(this).removeClass(&quot;ms-alternating&quot;);	
	});	
}

function removeSelectedDiv(obj){
var objVal = obj.text();
var objVal = handleSeparatorChar(objVal,true);
obj.parents('td:first').find('select').append(&quot;&lt;option value='&quot; + objVal + &quot;'&gt;&quot; + objVal + &quot;&lt;/option&gt;&quot;);
	obj.css({'background-color':'red'});
	obj.fadeTo(450,0,function(){obj.remove();});	
}

function handleSeparatorChar(str,remove){
var newStr = '';
	if(separatorChar==''){
		newStr = str;	
	}else{
		if(remove){
			newStr = str.substring(0,str.indexOf(separatorChar));
		}else{
			if(str.indexOf(separatorChar)&gt;-1){
				newStr = str;
			}else{
				newStr = str + separatorChar;
			}			
		}
	}
	return newStr;
}

function PreSaveAction(){
	$.each(arrFieldsToAccumulate, function(idx,item){
		var from = item.split('|')[0];
		var to = item.split('|')[1];
		// Find all selected values
		var str = '';
		$(&quot;.dummyClass_&quot; + from).each(function(){
			if($(this).text()!=''){
				str += $(this).text() + &quot;n&quot;;
			}
		});
		// Insert the values in the hidden field	
		$(fields[to]).find(':input').val(str);
	});
return true; 
}

function init_fields(){
  var res = {};
  $(&quot;td.ms-formbody&quot;).each(function(){
	  if($(this).html().indexOf('FieldInternalName=&quot;')&lt;0) return;
	  var start = $(this).html().indexOf('FieldInternalName=&quot;')+19;
	  var stopp = $(this).html().indexOf('FieldType=&quot;')-7;
	  var nm = $(this).html().substring(start,stopp);
	  res[nm] = this.parentNode;
  });
  return res;
}

Save the file as “AccumulateSelectionsToMultilineText.js” and upload to the document library or folder as described above.

How to set the fields as required:
Open the file “AccumulateSelectionsToMultilineText.js” and remove the function PreSaveAction(). Then you add this modified PreSaveAction(), and the lines for setting the red “required field” star after the label to the CEWP code.

You can NOT set the field as requires under list settings.

// Red star
$(fields['Choice']).find('.ms-formlabel h3').append(&quot;&lt;span class='ms-formvalidation'&gt; *&lt;/span&gt;&quot;);
$(fields['Choice2']).find('.ms-formlabel h3').append(&quot;&lt;span class='ms-formvalidation'&gt; *&lt;/span&gt;&quot;);

function PreSaveAction(){
var okToSave = true;
	$.each(arrFieldsToAccumulate, function(idx,item){
		var from = item.split('|')[0];
		var to = item.split('|')[1];
		// Find all selected values
		var str = '';
		$(&quot;.dummyClass_&quot; + from).each(function(){
			if($(this).text()!=''){
				str += $(this).text() + &quot;n&quot;;
			}
		});
		// Insert the values in the hidden field
		$(fields[to]).find(':input').val(str);
		// Remove validation message to avoid multiple messages
		$(fields[from]).find('.ms-formbody div.ms-formvalidation').remove();
		// Check if the &quot;to-field&quot; is empty, and that the field is set to required
		if(str=='' &amp;&amp; $(fields[from]).find('.ms-formlabel span.ms-formvalidation').length==1){			
			// Add validation message
			$(fields[from]).find('.ms-formbody').append(&quot;&lt;div class='ms-formvalidation'&gt;You must specify a value for this required field.&lt;/div&gt;&quot;);
			// Set &quot;save item&quot; to false
			okToSave = false;		
		}

	});
// Returns true or false
return okToSave; 
}

Please ask if something is not clear to you.

Alexander

Narrowing list form to one column

Updated 10.10.2009: To use this script with the script Headings in SharePoint Forms – jQuery you must set the parameter “stretch” for the heading script to false. You must also call the heading script before the “Narrowing list form to one column-script”.

I have made a tiny update to the heading script to support setting the backgound color when using it with “Narrowing list form to one column-script”.


I got a request for a solution to narrow down the list form to one column with the “formlabel” above the “formbody”.
This is actually a very simple task.

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.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

Add a CEWP below your NewForm list-form (and EditForm if you like) like this:
IMG

Add this code to the CEWP:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
$(document).ready (function() {	
	// This image sets the width of the form to min 590px - it must be removed
	$('#onetIDListForm img[width=590]').remove();	
});

$(&quot;td.ms-formlabel&quot;).each(function(){
	// Get the html of the formlabel
	var label = $(this).html();	
	// Insert the label over the formbody
	$(this).parents('tr:first').find('.ms-formbody').prepend(label);
	// Remove the original label
	$(this).remove();
	
});
&lt;/script&gt;

Note: If you use this solution with other solutions that modifies the formbody – like the Wrap choice-field in multiple columns, you have to call this script last to have the “formlabel” added in the right position.

Your end result should look like this:
IMG

As always – ask if you do not understand how to use this script

Alexander

Get variables in a script from another list

This one is a follow-up on the two previous posts on manipulating form labels, but the technique can be used for many other scenarios.

I will show you how to use entries from another list as “resources” for a script by querying the “resources-list” for variables to use in the script.

Because i use the same scenario as in the two previous posts, you must read them before proceeding with this one.

The array i used to populate the labels for each option in the choice list is now moved out in another list, and we “ask for it” with a CAML-query to the web-service lists.asmx.

Create a new list like this:
IMG
These are all the actual “FieldInternalNames” (Fields get their “FieldInternalName” first time created – any later modification of the name affects only their “DisplayName”).

The NewForm looks like this:
IMG

The fields are used like this:

  • ListGuid: This is the list Guid of the list using this resource.
  • Title: This is the FieldInternalName of the column to use the resource in.
  • Val: This is the actual value to return.
  • Description: This is used to describe the use of this “resource”.

Here is the form filled for our need in this example:
IMG

You must refer two more scripts like this:
IMG

The scripts “interaction.js” and “stringBuffer.js” is created by Erucy and published on CodePlex.

You will need the list GUID of your “resources-list” and the list you will insert the resources in. Replace the one in the script (resourcesListGuid – line 34 in the script) and the one in the picture above and the one in line 13 with your own!

I have made the “resources-list” more complex than i needed for this example, but by adding the “ListGuid” column i prepare the list so that it can be used by many different lists without having to think about using unique names for the columns in the different lists.

The script is now modified like this:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/interaction.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/stringBuffer.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
fields = init_fields();

var myNewLabel = &quot;&lt;br&gt;&lt;div&gt;Here is some custom text added by adressing the formlabel with jQuery!&lt;/div&gt;&quot; +
				 &quot;&lt;br&gt;&lt;div&gt;You can insert images to:&lt;br&gt;&lt;img src='/test/English/Shared%20Documents/jQuery_img.jpg' border='0'&gt;&lt;/div&gt;&quot;

$(fields['MyChoice']).find(&quot;.ms-formlabel h3&quot;).after(myNewLabel);

// Lookup the array values from another list and split it to create an array
arrMyChoice = getExternalResources('3264E665-228B-4A08-970C-4CE5E871A002','MyChoice').split(',');

// Call the script that inserts the descriptions
descriptionBeforeChoice('MyChoice',arrMyChoice,300);

function descriptionBeforeChoice(FieldInternalName,arrName,widthOfCustomLabel){
	$(fields[FieldInternalName]).find(&quot;.ms-formbody&quot;).find(&quot;:checkbox&quot;).each(function(idx){
		// Add alternating style to make it easier to follow the lines in the form
		var trClass = '';
		if(idx%2==0){
			trClass = 'ms-alternatingstrong';
		}
		$(this).before(&quot;&lt;span style='display:inline-block;width:&quot; + widthOfCustomLabel + &quot;;white-space:nowrap'&gt;&quot; + arrName[idx] + &quot;&lt;/span&gt;&quot;)
			.parent().css({'white-space':'nowrap'})
			.parents('tr:first').addClass(trClass);
	});
}

function getExternalResources(ListGuid,ElementTitle){ 
// ListGuid can be swapped with DisplayName
// ElementTitle is here the FieldInternalName of the field to add the resources to
var resourcesListGuid = &quot;{7008EA8E-623D-4F80-A70C-35C0F71E5FB0}&quot;; // GUID of the &quot;resources-list&quot; - can be swapped with DisplayName 
var query = &quot;&lt;Where&gt;&lt;And&gt;&lt;Eq&gt;&lt;FieldRef Name='ListGuid' /&gt;&lt;Value Type='Text'&gt;&quot; + ListGuid + &quot;&lt;/Value&gt;&lt;/Eq&gt;&quot; +
			&quot;&lt;Eq&gt;&lt;FieldRef Name='Title' /&gt;&lt;Value Type='Text'&gt;&quot; + ElementTitle + &quot;&lt;/Value&gt;&lt;/Eq&gt;&lt;/And&gt;&lt;/Where&gt;&quot;;
wsBaseUrl = L_Menu_BaseUrl + '/_vti_bin/';
var res = queryItems(resourcesListGuid,query,['Val'],1);
	if(res.count==-1){
		alert(&quot;An error occured in the query:n&quot; + query);
	}else{
		return res.items[0]['Val'];
	}
}

function init_fields(){
  var res = {};
  $(&quot;td.ms-formbody&quot;).each(function(){
	  if($(this).html().indexOf('FieldInternalName=&quot;')&lt;0) return;	
	  var start = $(this).html().indexOf('FieldInternalName=&quot;')+19;
	  var stopp = $(this).html().indexOf('FieldType=&quot;')-7; 
	  var nm = $(this).html().substring(start,stopp);
	  res[nm] = this.parentNode;
  });
  return res;
}
&lt;/script&gt;

The end result looks like in the previous post:
IMG

As always – ask if something is unclear!
Alexander