All posts by Alexander Bautz

Count groups in grouped list view

This is a short one on counting groups in a grouped list view like this (group count in the list view toolbar):
IMG

Note: This counts only visible groups. If you set the “Number of groups to display per page” in the list view settings you will get max that number of groups when counting. An alternate approach would be to query the list for the total number of unique items based on the items the view is grouped by.

Add a CEWP below the list view with this code (alter the location of jQuery as needed):

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

// Grouping on level 1
var CountGrouping1 = $(".ms-listviewtable td.ms-gb").length;
var NameGrouping1 = $(".ms-listviewtable td.ms-gb:first a:eq(1)").text();

// Grouping on level 2
var CountGrouping2 = $(".ms-listviewtable td.ms-gb2").length;
var NameGrouping2 = $(".ms-listviewtable td.ms-gb2:first a:eq(1)").text();

var str = NameGrouping1 + "'s: " + CountGrouping1 + " | " + NameGrouping2 + "'s: " + CountGrouping2;

$("td.ms-toolbar[width='99%']").append("<div class='ms-listheaderlabel' style='text-align:center;margin-top:-15px'>" + str + "</div>");

</script>

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

Ask if something is unclear.

Regards
Alexander

SharePoint list’s or document library’s: Primary key in selected field

05.01.2010 Small update to hide the “OK-button” if the “keyIsNotUniqueCount” is greater than 0.
25.11.2009 Small update to the script for placing the image correctly when used with the headings script.

In this article I will give you a solution for adding “primary key support” to a list or a document library with JavaScript.

This will work with fields of type “Single line of text”, “Multiple lines of text (Plain text)” and “Number”. Note that if you activate this feature for a field of type “Number”, it strips off all other than numbers 0-9. No spaces, commas or periods are allowed. This is done to avoid conflicts based on different formats used in different language settings.

You can enable this feature for more than one field in a list or document library.

Note: This does only work in NewForm and EditForm, not if edited in DataSheet.

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 “PrimaryKey.js” is found below.

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

The last file in this screen-shot is the Right click and select Save picture as. Right click on the image and select “Save picture as”.

Add a CEWP below your list-form in NewForm and EditForm.
Add this code:

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
<script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
<script type="text/javascript" src="/test/English/Javascript/PrimaryKey.js"></script>
<script type="text/javascript">
   // Enables "Primary key" on the "Title-field"
   ensurePrimaryKey('Title','','/test/English/Javascript/PrimaryKey.gif','');
</script>

Your “Title-field” will look like this:
IMG

The check is attached to the “blur” event, and triggers when you removes focus on the field. If you try to add a “non-unique-value” to that field, you end up with this warning, and cannot save the list item:
IMG

If used with a field of type “Number”, the code strips away spaces, commas and periods as described above.

Parameters explained:

  • FieldInternalName: FieldInternalName of the field to add this feature to
  • PrimaryKeyViolationWarning: [optional] The text shown under the field if the key is not unique.
  • keyImageSrc: [optional] Image source for the “key.image” added before the field label. If not supplied it default’s to “/_layouts/images/prf16.gif”.
  • PrimaryKeyHoverImageText: [optional] Description text if hovered over the “key-image”.

Sourcecode for the file “PrimaryKey.js”:

/* Primary key for lists or Document libraries
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * v1.1
 * LastMod: 05.01.2010
 * ---------------------------------------------
 * Include reference to:
 *  jquery - http://jquery.com
 *  interaction.js - http://spjslib.codeplex.com/
 *  stringBuffer.js - http://spjslib.codeplex.com/
 * ---------------------------------------------
 * Call from a CEWP below the list form in NewForm orEditForm like this:
	<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
	<script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
	<script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
	<script type="text/javascript" src="/test/English/Javascript/PrimaryKey.js"></script>
	<script type="text/javascript">
		// Enables primary key for the "Title-field"
		ensurePrimaryKey('Title','This field's value has to be unique for this list.','/test/English/Javascript/PrimaryKey.gif','Primary key is enabled for this field');
	</script>
*/

if(typeof(fields)=='undefined')fields = init_fields();
function ensurePrimaryKey(FieldInternalName,PrimaryKeyViolationWarning,keyImageSrc,PrimaryKeyHoverImageText){
	if(fields[FieldInternalName]!=undefined){
		listDisplayName = $("h2.ms-pagetitle a").text();
		keyIsNotUniqueCount = 0;
		// If PrimaryKeyViolationWarning is not defined, default to this text
		if(PrimaryKeyViolationWarning==undefined || PrimaryKeyViolationWarning==''){
			var PrimaryKeyViolationWarning = "This field's value has to be unique for this list.";
		}
		// If PrimaryKeyHoverImageText is not defined, default to this text
		if(PrimaryKeyHoverImageText==undefined || PrimaryKeyHoverImageText==''){
			var PrimaryKeyHoverImageText = "Primary key is enabled for this field";
		}
		if(keyImageSrc==undefined || keyImageSrc==''){
			keyImageSrc = "/_layouts/images/prf16.gif";
		}
		// If number - trim off all spaces, commas and periods
		if($(fields[FieldInternalName]).html().match('SPFieldNumber')!=null){
			$(fields[FieldInternalName]).find(':input').keyup(function(e){
				var currVal = $(this).val();
				$(this).val(currVal.replace(/[^0-9]/g,''));
			});
		}
		
		// Determine where to put the image - if used with the Heading-script		
		if($(fields[FieldInternalName]).find("h3:has('div')").length>0){
			var insertImageHere = 'h3 div';
		}else{
			var insertImageHere = 'h3';
		}
		
		// Add blur function
		$(fields[FieldInternalName]).find(':input').blur(function(){
			// Check if input value is unique in this list
			checkPrimaryKey(FieldInternalName,$(this),PrimaryKeyViolationWarning);
		})
		// Add key image before label
		.parents('tr:first').find(insertImageHere)
		.prepend("<img title='" + PrimaryKeyHoverImageText + "' src='" + keyImageSrc + "'>");
	}
}

function checkPrimaryKey(FIName,keyField,warningText){
wsBaseUrl = L_Menu_BaseUrl + '/_vti_bin/';
var ItemId = getIdFromFormAction(); // Returns 0 if NewForm
var keyFieldVal = keyField.val().replace(/&/g,'&');

	if(ItemId==0){ // NewForm
		var query = "<Where><Eq><FieldRef Name='" + FIName + "'/><Value Type='Text'>" + keyFieldVal + "</Value></Eq></Where>";
	}else{ // EditForm - skip current ID
		var query = "<Where><And><Eq><FieldRef Name='" + FIName + "'/><Value Type='Text'>" + keyFieldVal + "</Value></Eq>" +
					"<Neq><FieldRef Name='ID'/><Value Type='Counter'>" + ItemId + "</Value></Neq></And></Where>";
	}
	var res = queryItems(listDisplayName,query,['ID']);
	if(res.count==-1){
		alert("An error occured in the query:n" + query);
	}else if(res.count>0){
		keyIsNotUniqueCount = keyIsNotUniqueCount + 1;
		keyField.parents('td:first').find(".customPrimaryKeyAlert").remove();
		keyField.parents('td:first').append("<div class='customPrimaryKeyAlert' style='color:red'>" + warningText + "</div>");
	}else{
		keyField.parents('td:first').find(".customPrimaryKeyAlert").remove();
		if(keyIsNotUniqueCount>0){
			keyIsNotUniqueCount = keyIsNotUniqueCount - 1;
		}
	}
	// Hide button
	if(keyIsNotUniqueCount>0){
		$("input[id$='SaveItem']").hide();
	}else{
		$("input[id$='SaveItem']").show();
	}
}

// This function gets the list item ID from the form's action-attribute
function getIdFromFormAction(){
var action = $("#aspnetForm").attr('action');
var IdCheck = action.substring(action.indexOf('?')).indexOf('ID=');
	if(IdCheck==1){
	var end = action.indexOf('&');
		if(action.indexOf('&')<0){
			id = action.substring(action.indexOf('ID=')+3);
		}else{
			id = action.substring(action.indexOf('ID=')+3,end);
		}
	}else{
		id = 0; // Called from NewForm returns 0
	}
	return id;
}

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

Save as “PrimaryKey.js” and upload to the “script-library” as shown above.

This is not a “guaranteed” primary key, as it does not work in datasheet-editing, and I’m sure someone finds a way to trick it. I’m nevertheless confident that someone can make use of this code.

Let me know if something is unclear.

Regards
Alexander

Redirect on NewForm and EditForm another method

This is another method for redirecting a user to a custom page on “OK” and another page on “Cancel”.

I have described two methods in this previous article. This method is a god replacement for the “simple redirect” described in the previous article.

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

Add a CEWP below your list-form in NewForm or EditForm, 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();
// Where to go when cancel is clicked
goToWhenCanceled = '/test/English/YouCanceled.aspx';

// Edit the redirect on the cancel-button's
$('.ms-ButtonHeightWidth[id$="GoBack"]').each(function(){
    $(this).click(function(){
			STSNavigate(goToWhenCanceled);
	  })
});

// Edit the form-action attribute to add the source=yourCustomRedirectPage
function setOnSubmitRedir(redirURL){
var action = $("#aspnetForm").attr('action');
var end = action.indexOf('&');
	if(action.indexOf('&')<0){
		newAction = action + "?Source=" + redirURL;
	}else{
		newAction = action.substring(0,end) + "&Source=" + redirURL;
	}
$("#aspnetForm").attr('action',newAction);
}

/*
// Use this for adding a "static" redirect when the user submits the form
$(document).ready(function(){
	var goToWhenSubmitted = '/test/English/ThankYou.aspx';
	setOnSubmitRedir(goToWhenSubmitted);
});
*/

// Use this function to add a dynamic URL for the OnSubmit-redirect. This function is automatically executed before save item.
function PreSaveAction(){
// Pass a dynamic redirect URL to the function by setting it here,
// for example based on certain selections made in the form fields like this:
	var mySelectVal = $(fields['MySelect']).find(':radio:checked').next().text(); 
	if(mySelectVal=='Option one'){
		var dynamicRedirect = '/test/English/YouSelectedOptionOne.aspx';
	}else if(mySelectVal=='Option two'){
		var dynamicRedirect = '/test/English/YouSelectedOptionTwo.aspx';
	}	
	
	// Call the function and set the redirect URL in the form-action attribute
	setOnSubmitRedir(dynamicRedirect);
	
	// This function must return true for the save item to happen
	return true;
}

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>

This script is by default setup with a “dynamic” redirect for “OK” based on the selection made in a “Choice-field” of type “Radio Buttons” with the options “Option one” and “Option two”.

The “OK” redirect can be set to a “static” value if you comment out the function “PreSaveAction()” and uncomment the “$(document).ready(…” function.

The cancel-redirect is set in the top pf the script in the variable “goToWhenCanceled”. The script modifies the “click” attribute of both cancel-buttons and adds this redirect.

Ask if something is unclear

Regards
Alexander

Identify content type to execute content type specific code

In another post i received a request on how to identify the content type in NewForm to execute “content type specific code”. Here’s a quick description of one method.

The method relies on a script, init_fields(), which loops trough all fields in the form and makes an object of all table rows and their HTML. This way all fields can be addressed by their FieldInternalName, returning the full HTML of that field.

The function init_fields() is a modified version of Erucy’s function for finding fields in a SharePoint form. My modified version uses FieldInternalName rather than DisplayName to locate the fields.

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 code below uses the FieldInternalName of a specific field to ensure that the field is rendered – if so – it executes the code wrapped in that “if-statement”. The field used to identify the ContentType must reside only in that content type.

Add a CEWP belowit is essential that it is placed below – your list-form as briefly described here, 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();
/*
 This example shows how you can check what ContentType is used by checking if
 a field you know is in that specific ContentType is rendered
*/

// Check if the field with FieldInternalName of "OnlyInContentType1" is rendered
if(fields['OnlyInContentType1']!=undefined){
	alert("This is content type nr 1");
	// Execute any code that addresses the first content type
}

// Check if the field with FieldInternalName of "OnlyInContentType2" is rendered
if(fields['OnlyInContentType2']!=undefined){
	alert("This is content type nr 2");
	// Execute any code that addresses the second content type
}

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 code above does work in NewForm, DispForm and EditForm.

To get the “FriendlyName” of the content type in DispForm or EditForm you can use the script below. This script also enables you to hide the “Content type selector” from EditForm.

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

// This example shows how you can get the "FriendlyName" of the ContentType
// You can optionally hide the "ContentType selector from EditForm"

// Get the name and hide the selector
var contentType = getContentFriendlyNameOptionalHide(true);
alert(contentType);

function getContentFriendlyNameOptionalHide(hide){
if(hide){
	$("select[id$='ContentTypeChoice']").parents('tr:first').hide();
}
	// EditForm
	var value = $("select[id$='ContentTypeChoice']").find('option:selected').text();
	// DispForm
	if(value==''){
		value = $("span[id$='InitContentType']").text();
	}
return value;
}
</script>

Ask if something is unclear.

Regards
Alexander

Preview metadata in list view on mouseover

12.09.2011 A new version is posted here.

30.07.2010 A major update of the script to tidy up the code and to support previewing in a image library. Please read trough the article to get the changes to the CEWP code. The solution is tested in IE 8, Firefox v3.6.8 and in Google Chrome v5.0.375.125.

22.06.2010 Small update in line 118 and 125 to prevent “star” to be appended to lookup columns.

23.03.2010 Updated the code for “Preview_DispForm_metadata.js”. This update fixed compatibility with folders (thanks to Deano for finding the bug). Added support for a mix of lists and document libraries in the same webpart page.

19.02.2010 Fixed a bug if two different document libraries were present in the same webpartpage. The file “Preview_DispForm_metadata.js” is updated. Thanks to Ben for finding the bug.

09.01.2010: Fixed a major performance issue when viewing only selected fields from the metadata. Replace the code for the file “Preview_DispForm_metadata.js” to get the latest fixes.

10.12.2009: Fixed a hard coded “hoverImg” in the code – thanks to Amy.


By request from some of my readers i have, with basis in a solution created by Paul Grenier and published on EndUserSharepoint, made a solution that preview’s metadata from a list item or a document on mouse over.

The script i used as basis previewed metadata from DispForm in a CEWP beside a calendar view.

This modification adapts it to present a “floating” pop-up on mouse over when hovering over a table row, a calendar item, or on a small image added before a selected field.

The original script, made by Paul Grenier, previewed the full form from DispForm. I have adapted it so that one can display the full form, or specify an array of columns to display.

This script can be used in plain list view, grouped list views and calendar views.

New in this version is that the ID column must be in the view (not true for calendar view). The column can be hidden in the script.

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, be sure to update the script reference in the sourcecode.

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

Add a CEWP below the list view and add the code – examples shown below the screen-shots.

Here are some screenshots and the CEWP code:
Plain list view – all fields
IMG

<script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/Preview_DispForm_metadata.js"></script>

To hide the ID column, change the CEWP code like this:

<script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/Preview_DispForm_metadata.js"></script>
<script type="text/javascript">
    hideIdColumn = true;
</script>

Plain list view – selected fields
IMG

<script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/Preview_DispForm_metadata.js"></script>
<script type="text/javascript">
    hideIdColumn = true;
    arrOfFieldsToShow = ['MultilinePlainText','Responsible'];
</script>

“hoverImg” used
IMG

<script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/Preview_DispForm_metadata.js"></script>
<script type="text/javascript">
    hideIdColumn = true;
    arrOfFieldsToShow = ['MultilinePlainText','Responsible'];
    hoverImg = '/_layouts/images/OPENDB.GIF';
    hoverImgDescription = 'Hover mouse over this image to preview the metadata'; // If left blank, no description is displayed in the pagetitle area
    prependHoverImageTo = 'LinkTitle'
</script>

Parameters explained:

  • hideIdColumn: true to hide the ID column. Defaults to false
  • arrOfFieldsToShow: Array of fields to show. Defaults to all fields.
    To have only a selection of fields, add to the array like this: [‘Title’,’MultilinePlainText,’Responsible’].
    To have only the value and not the label showing, add to the array like this: [‘MultilinePlainText|0’]
  • hoverImg: If you want to hover over an image and not the whole row, add the “src” to the image here. You must also set the parameter “prependHoverImageTo”.
  • prependHoverImageTo: A FieldInternalName to prepend the “hoverImg” to.
  • hoverImgDescription: A description that will be added to the page title area.

All parameters are optional.

Sourcecode for “Preview_DispForm_metadata.js” is found here

Note:

When new versions are released, they will be placed in a folder with the version number as label. Be sure to download the latest version.

If you are using a browser other than IE, right click the file and select “Save link as” or “Save linked content as…”.

Ask if something is unclear.

Regards
Alexander

Collect input from custom input fields and store in multiline plain text field

16.11.2009 Fixed an error found by Marc Verner, resulting in values returning “undefined”. This error var introduced by my previous update because i didn’t test it thoroughly…

I have added some code to show how to use this code with multiple fields. This code is commented out, but is found in lines 6, 10 and 54-63. Uncomment these lines and you are good to go with another field with FieldInternalName “MultilinePlain2”. I have also added an attribute “labelPosition”, value “above” or “before” to determine label position.

14.11.2009 Small update on alignment of the input field – thanks to Larry. There are now two options on alignment. the default is to have the label above the input-field. Comment out line 17 and activate line 19 to have the label before the input-field (note that a long label will fall behind the input-field).

I got a request that i thought was worth doing a post on. Its from Marc Verner and sounded like this:

Hey Alexander,
I currently have a MS Word based form that contains a 2 column by 10 row table where users provide up to 10 keycodes and their corresponding descriptions. I am hesitant to make 20 sharepoint variables to capture this since it will make a mess of the form – and I don’t need to query or report on these fields. Instead I’m looking for a possible solution for pre-populating a rich text field with a table template including column names. This way when a user creates a new item, they will see the familiar table and simply fill it in as per usual.
Not sure if its possible but you have really amazed me so far so figured I’d ask =)
Many thanks,
Marc

I do not like SharePoint’s rich text fields as the clutter the HTML-code to the non recognizable when editing. This solution is therefore based on generating some custom input fields and storing the result in a multi line text field of type “plain text”.

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

You start with a standard multiline text field like this:
IMG

Add the script, and you end up with this:
IMG

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

And add this code:
You must replace any occurrence of “MultilinePlain” with your FieldInternalName

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Array to create the input fileds from
var arr = ['Label 1','Long Label 2','Even longer Label 3','Label 4','Label 5'];
//var arr2 = ['Label 6','Long Label 7','Even longer Label 8','Label 9','Label 10'];

// Call the script with the array, and the FieldInternalName of the multiline text field
generateInputAndStoreInMultilineText(arr,'MultilinePlain','above',300);
//generateInputAndStoreInMultilineText(arr2,'MultilinePlain2','before',300);

function generateInputAndStoreInMultilineText(arrOfLabels,FieldInternalName,labelPosition,widthOfInputField){
if(widthOfInputField==undefined)widthOfInputField=250;
// Hide the multiline text field
$(fields[FieldInternalName]).find(".ms-formbody :input:last").hide().next().hide();
	var customInputFields = '';
	// Loop trough all "Labels" and create the input field
	$.each(arrOfLabels,function(idx,item){
		// Label position
		if(labelPosition=='above'){
			customInputFields += "<div id='customInput_" + idx + "' value='" + item + "' style='padding:2px'>" + item + "<br><input type='Text' style='width:100%;margin:0 13 0 0;'></div>";
		}else if(labelPosition=='before'){
			customInputFields += "<div id='customInput_" + idx + "' value='" + item + "' style='padding:2px;'>" + item + "<div style='text-align:right;margin: -17px 13px 0 0;'><input type='Text' style='width:" + widthOfInputField + "px'></div></div>";
		}
	});
	// Insert the custom input fields
	$(fields[FieldInternalName]).find('.ms-formbody').prepend(customInputFields);
	// Handle page refresh due to form validation, and preserve the values in the custom inputs
	$(document).ready(function(){
	// Read the values from the hidden multiline textfield
		if($(fields[FieldInternalName]).find(".ms-formbody :input:last").val()!=''){
			// Split the values
			var raw = $(fields[FieldInternalName]).find(".ms-formbody :input:last").val();
			var split = raw.split('n');
			// Insert the values in the correct "custom input"
			$(fields[FieldInternalName]).find(".ms-formbody div[id^='customInput_']").each(function(idx){
			var splitAgain = split[idx].split(': ');
				$(this).val(splitAgain[0]);
				$(this).find('input').val(splitAgain[1]);
			});
		}
	});
}

function PreSaveAction(){
var valToSave = '';
// Build the content to write to the hidden multiline field
$(fields['MultilinePlain']).find(".ms-formbody div[id^='customInput_']").each(function(){
	valToSave += $(this).val() + ": " + $(this).find('input').val() + "n";
});
// Write to multiline field
$(fields['MultilinePlain']).find(".ms-formbody :input:last").val(valToSave);

/*
// Field nr 2
var valToSave = '';
// Build the content to write to the hidden multiline field
$(fields['MultilinePlain2']).find(".ms-formbody div[id^='customInput_']").each(function(){
	valToSave += $(this).val() + ": " + $(this).find('input').val() + "n";
});
// Write to multiline field
$(fields['MultilinePlain2']).find(".ms-formbody :input:last").val(valToSave);
*/
return true; // Must return true for item to be saved
}

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 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 script handles page refresh due to form validation, and preserves the values in the custom input fields (it reads them back from the hidden text field). The code can be used for both NewForm and for EditForm due to the same logic.

The values are stored in a proper format to present in DispForm and in list view’s like this:
IMG
IMG

Read here how to find the FieldInternalName of your field

Don’t hesitate to ask if all is not clear

Regards
Alexander

Move site actions to the left

21.02.2010: Updated the post with the code for floating the site action menu to the right on the screen (as requested by Larry).

This one proved a bit tricky because the site action menu is part of the master page.

See codeblock below for updated code. Please let me know if you find any bugs.


After i posted the solution to Move view selector to the left, i got a request from Charlie Epes for the same solution regarding the “Site Actions-menu”.

This is the default placement of the Site Actions-menu:
IMG

Here the menu is inserted after the last toplink (dynamic):
IMG


Here is how it’s done
Add a CEWP below the list view, and add this code (alter the location of the jQuery-scipt as needed)

<script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$("table.ms-bannerframe table:first td:last").after($("table.ms-bannerframe td:last"));
</script>

Code for floating the menu to the right (replace the code supplied above with this one):

<script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
// Site action float right
$(document).ready(function(){
	setTimeout(function(){
		siteActionFloatRight();
	},500);
});

function siteActionFloatRight(){
	var menuWidth = $("table.ms-siteaction").width();
	var doc = $(document).width();
	var win = $(window).width();
	var scr = $(window).scrollLeft();

	left = doc-win-scr+menuWidth;
	if(left<120){
		left=100;
	}
	// Move the site action menu to the new position
	$("table.ms-siteaction").css({'position':'absolute','top':0,'left':-left});	
}

// Handle resize and scroll
$(window).resize(function() {
	siteActionFloatRight();
}).scroll(function() {
	siteActionFloatRight();
});

// Make it adapt to changing document width due to expanding groups
$("td[class^='ms-gb']").click(function(){
	setTimeout(function(){
		siteActionFloatRight();
	},250);
});
</script>

Regards
Alexander

Move view selector to the left

06.02.2010 Added another method for floating the view selector on the right side of the page.


I got a request from “tecrms” that sounded like this:

As you know on all list views and document views, the view selector is on the right hand side of the menu bar. This can make it quite cumbersome for users looking at lists with many columns to change the view. A better option would be for the view selector to be on the left hand side and right hand side of the menu bar. I know I can move the view selector via SPD but would rather use a JavaScript options if one was available. Would this be something you would be interested in creating?

It’s often harder to think out the question than to actually solve the issue…

This is the default placement of the view-selector:
IMG

Here the selector is inserted after the “Settings-menu”:
IMG


Here is how it’s done
Add a CEWP below the list view, and add this code (alter the location of the jQuery-scipt as needed)

<script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$("td.ms-toolbar:last").insertBefore($("td.ms-toolbar[width='99%']"));
</script>

Use this code for a floating menu on the right side of the page:

<script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	viewMenuFloatRight();
});

function viewMenuFloatRight(){
	var top = $("td.ms-toolbar:last").offset().top+2;
	var menuWidth = $("td.ms-toolbar:last table").width()+15;
	var left = $(window).width() - menuWidth + $(window).scrollLeft();	
	// Position the menu
	$("td.ms-toolbar:last table").css({'position':'absolute','top':top,'left':left});
	// Paging
	$("td.ms-toolbar td[id='topPagingCellWPQ1'] table").css({'position':'absolute','top':top,'left':left-50});
}

// Handle resize and scroll
$(window).resize(function() {
	viewMenuFloatRight();
}).scroll(function() {
	viewMenuFloatRight();
});
</script>

Regards
Alexander