Category Archives: SharePoint 2007

Poll for SharePoint

March 15, 2015: I have updated this solution. You find v2.0 here.

Please note: The Google Image Charts used in this solution is deprecated and will stop working April 20, 2015.

Change log
January 28. 2014
v1.54 fixes one incompatibility with SP 2013. I have not fully tested this so please let me know if you find any bugs.

July 01. 2013 v1.53: The sort order of answers in chart now reflects the order given in the setup. I have removed some script references so that you now must refer spjs-utility.js – get it here

You must update the CEWP code to include reference to spjs-utility.js

15.12.2011 v1.5.1: Bugfix in the file “PollForSharePoint.js” – line 238. The property “listBaseUrl” were missing – thanks to Jaap Dijkma for finding this bug.


04.12.2011 I have updated the solution to support putting the list in a central location. See “listBaseUrl” below.


22.10.2011 Updated the code to support free input rather than predefined answers – as requested by Claudia:

Hi, thank you for this wonderful piece of code, I think it’s great and we use it on our intranet :).
I wondered if it is possible to use a single line of text for free input instead of radiobuttons with preset answers?
We like to use the poll for ‘brandtagging’ so that people can type keywords.
Just wondering…..
thanks! Claudia

I thought this was a clever idea and have implemented this in v1.4. See updated CEWP code and description below.


17.08.2011 Updated the code with these changes:

  • Lets you view the results and come back to answer.
  • Tidied up the code.
  • The charts now supports https (Thanks to Google).
  • Removed the poll question from the chart title to preserve the formatting.

01.03.2011 Updated the code to fix a bug when “singleResponse” is true. Thanks to “Al”. I have also included two more settings in the “argObj”: qStyle and aStyle. These sets the CSS style of question and answers. See CEWP code below.


28.11.2010 Updated the code to support special characters in the poll question and answers. Thanks to Christophe for the tip.


This code lets you generate polls using JavaScript/jQuery only. No need for server side installed WebParts.

Poll
IMG

Result with column chart
IMG

Result with bar chart
IMG

Result with pie chart
IMG

Result with “table chart”
IMG

Already answered
IMG

Not active
IMG

Finished
IMG

The charts are generated using Google Chart Tools / Image Charts (aka Chart API).


Create a custom list with the following fields

  • Answer: Single line of text
  • Question: Single line of text

Name it anything you like, but keep the display name fairly simple (no special characters) as you will use the display name in the CEWP code.

CEWP code

The CEWP code below refers jQuery from Google. If you have a local copy of jQuery you can change the script src. You find the code for the file “PollForSharePoint.js” at the bottom of the page. In this example the file “PollForSharePoint.js” is placed in a document library named “Javascript”.

NOTE: You must change the script src for the file “PollForSharePoint.js” and “spjs-utility.js” to point your instance of the files – the CEWP code will not work unless you do this.

Place this code where you want the poll to appear:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/Poll/spjs-utility.js"></script>
<script type="text/javascript" src="/test/English/Javascript/Poll/PollForSharePoint.js"></script>
<script type="text/javascript">

buildQueryWP({pollAnswerListName:'PollA',
				listBaseUrl:L_Menu_BaseUrl,				
				id:'myPoll_01-03-2011', // Allowed characters id a-z, 0-9 - and _
				start:'10/22/2011', // format: mm/dd/yyyy
				end:'11/10/2011', // format: mm/dd/yyyy
				singleResponse:false,
				q:"What is your<br />favorite junk food?",
				qStyle:'font-size:small;font-weight:bold;color:gray',
				aStyle:'font-size:xx-small',
				a:['Pizza','Hot dog','Hamburger','Neither of them'], // Leave empty for free input				
				color:['32CD32','FFCC11','FF3300','C0C0C0'],
				forceLowerCaseAnswer:false, // Group result by lowercase				
				chart:'col', // table, bar, col or pie
				height:100,
				width:450});
</script>

You can control these values in the top of the file “PollForSharePoint.js”:

var submitLinkText = 'Submit';
var backLinkText = 'Back';
var showResultBtnText = 'Show result';
var pollNotActiveText = 'The poll is not active prior to {0}';
var pollEndedText = 'The poll ended on {0}';
var alreadyRespondedText = 'You answered: ';
var totalResponsesLabel = "Total responses: ";

Object attributes explained

  • pollAnswerListName: DisplayName or GUID of the list that stores the answers
  • listBaseUrl: The baseUrl of the site. This is like “/sites/hr” when the list is located in the site “hr” under “/sites”. Use L_Menu_BaseUrl (or omit the property) for current site. New in v1.5
  • id: The unique id of the poll. All poll answers are stored in a list and this id is used to separate each poll
  • start: Start date in the format mm/dd/yyyy
  • end: End date in the format mm/dd/yyyy
  • singleResponse: true for one reply per user, false for unlimited number of replies
  • q: Poll question. To have a linefeed in the question, use <br>
  • qStyle: CSS syntax style
  • aStyle: CSS syntax style
  • a: Answers in an array format. To use free input and not predefined answers, leave the array empty.
  • color: Colors for the chart in an array format. This must have the same length as the previous parameter – one color for each answer
  • forceLowerCaseAnswer: Primarily for use with free input to avoid getting two “series” when the only difference are uppercase characters. New in v1.4
  • chart: “bar” for bar chart, “col” for column chart, “pie” for pie chart or “table” for a plain table.
  • height: Height in pixels
  • width: Width in pixels

Regarding free input
If you leave the attribute “a” as an empty array, the user can supply free text as “answer”. When using free input, the result are automatically presented as a table.

Download code

The code for the file “PollForSharePoint.js”:
Download code from this location

Ask if anything is unclear.

Alexander

Toggle column visibility in list view

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


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

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


Change log:

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

19.05.2010 Modified code to support multiple list views in the same page. The code is not fully tested so please report any bugs. Only the code for the file ToggleColumnVisibility.js” has changed.

19.04.2010 Modified code to support “pre hiding” from query string parameter. Both the CEWP code and the file “ToggleColumnVisibility.js” has changed.


Here are a solution for toggling the columns visibility in a list view by adding a checkbox row above the list view. Remove the check to hide the column. recheck to show.

The solution dynamically adapts to the columns in the view.
IMG

IMG

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.4.2.min. If you download another version, please update the code in the CEWP.

The sourcecode for the file “ToggleColumnVisibility.js” is provided below.

Add this code to a CEWP below the list view:
For v1.3

&lt;script type=&quot;text/javascript&quot; src=&quot;../../Javascript/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/ToggleColumnVisibility.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
// To &quot;pre uncheck&quot; checkboxes, add names to this array
	var arrOfPreHiddenColumns = ['MyPeoplePicker','My multi line'];
// Pull columns to &quot;pre uncheck&quot; from the query string parameter &quot;ColumnsToHide&quot;
	var qStrPAram = getQueryParameters();
	var colFromQueryString = qStrPAram.ColumnsToHide;
	if(colFromQueryString!=undefined){
		arrOfPreHiddenColumns = arrOfPreHiddenColumns.concat(colFromQueryString.split(','));
	}
// Array of columns to skip
	var arrOfFieldInternalNamesToSkip = [];
// Call the script
	init_Checkboxes(arrOfPreHiddenColumns,arrOfFieldInternalNamesToSkip);
&lt;/script&gt;

For v1.4 on SP2007 and 1.x on SP2010

&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/ToggleColumnVisibility/ToggleColumnVisibility.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
// To &quot;pre uncheck&quot; checkboxes, add names to this array
	var arrOfPreHiddenColumns = ['MyPeoplePicker','My multi line','ID'];
// Array of columns to skip
	var arrOfFieldInternalNamesToSkip = [];
// Array of columns that will not render a checkbox
	var arrDoNotRenderCheckbox = ['LinkTitle','ID'];
	
// Call the script
	init_Checkboxes(arrOfPreHiddenColumns,arrOfFieldInternalNamesToSkip,arrDoNotRenderCheckbox);
&lt;/script&gt;

Regarding the variable “arrOfPreHiddenColumns”:
Refer fields by their FieldInternalName. The “Edit” button and multi line text fields however does not have their FieldIternalName present in the column header and therefore must be addressed by their DisplayName.

Passing columns to hide in the query string:
To hide columns by query string, pass them in the URL like this:
/test/English/Lists/ToggleColumnVisibility/AllItems.aspx?ColumnsToHide=MyNumberColumn,ID

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

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

Download

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

Ask if anything is unclear.

Regards
Alexander

Highlight row by value in Yes/No-column

08.10.2011 Updated with SharePoint 2010 code.


22.04.2010 Updated the code to support multiple views of the same list in the same page, as requested by Mich.

The file “HighlightRowByYesNoColumn.js” is updated.


In this post i will show you how to highlight a row in a list view based on the value in a column of type “Yes/No (check box)”. The code would work on other types of columns as well.

IMG
This is from a standard list view, it does also work in grouped view’s.

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 and insert 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/HighlightRowByYesNoColumn.js"></script>
<script type="text/javascript">
highlightRowByYesNoField('Yes','YesNo','#FFD700','Highlighted rows awaiting action...');
</script>

Parameters explained:

  • valToTriggerHighlighting: The text you want to trigger the highlighting on – “Yes”
  • FieldInternalName: The FieldInternalName of the column to get the value from – must be in view
  • highlightColor: The background color of the highlighted row
  • mouseOverOnRow: The mouse over message when hovered over a highlighted row

The sourcecode for the file “HighlightRowByYesNoColumn.js” looks like this:

SharePoint 2007
/* Highlight row in list view based on value in a Yes/No-column
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * v1.1
 * LastMod: 22.04.2010
 * ---------------------------------------------
 * Include reference to jquery - http://jquery.com
 * ---------------------------------------------
 * Call from a CEWP below the list view with 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/HighlightRowByYesNoColumn.js"></script>
	<script type="text/javascript">
		highlightRowByYesNoField('Yes','YesNo','#FFD700','Highlighted rows awaiting action...');
	</script>
*/

function highlightRowByYesNoField(valToTriggerHighlighting,FieldInternalName,highlightColor,mouseOverOnRow){
	if(typeof(valToTriggerHighlighting)!='undefined'){
		valToFind = valToTriggerHighlighting;
	}
	if(typeof(FieldInternalName)!='undefined'){
		fin = FieldInternalName;
	}
	if(typeof(highlightColor)!='undefined'){
		bgColor = highlightColor;
	}
	if(typeof(mouseOverOnRow)!='undefined'){
		mouseOver = mouseOverOnRow;
	}
	
	$("table.ms-listviewtable").each(function(){
		var thisListView = $(this);
		// Find colindex of YesNo-field
		thisListView.find(".ms-viewheadertr th").each(function(){
			if($(this).text()==fin){
				colIndex = $(this).attr('cellIndex');		
			}
		});
		
		// Loop trough all rows and highlight matched rows
		thisListView.find("tbody:not([id^='aggr']) tr:has(td.ms-vb2)[highlighted!='1']").each(function(){			
			var rowVal = $(this).find("td[cellIndex='"+colIndex+"']").text();
			if(rowVal==valToFind){
				$(this).attr({'highlighted':'1','title':mouseOver}).css({'background-color':bgColor});		
			}		
		});
	});
}

// Attaches a call to the function to the "expand grouped elements function" for it to function in grouped listview's
function ExpGroupRenderData(htmlToRender, groupName, isLoaded){
	var tbody=document.getElementById("tbod"+groupName+"_");
	var wrapDiv=document.createElement("DIV");
	wrapDiv.innerHTML="<TABLE><TBODY id="tbod"+groupName+"_" isLoaded=""+isLoaded+"">"+htmlToRender+"</TBODY></TABLE>";
	tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild,tbody);
highlightRowByYesNoField();
}
SharePoint 2010
/* Highlight row in list view based on value in a Yes/No-column
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * v1.1 for SharePoint 2010
 * LastMod: 08.10.2011
 * ---------------------------------------------
 * Include reference to jquery - http://jquery.com
 * ---------------------------------------------
 * Call from a CEWP below the list view with this code:
*/

function highlightRowByYesNoField(valToTriggerHighlighting,FieldInternalName,highlightColor,mouseOverOnRow){
	var fName;
	if(typeof(valToTriggerHighlighting)!='undefined'){
		valToFind = valToTriggerHighlighting;
	}
	if(typeof(FieldInternalName)!='undefined'){
		fin = FieldInternalName;
	}
	if(typeof(highlightColor)!='undefined'){
		bgColor = highlightColor;
	}
	if(typeof(mouseOverOnRow)!='undefined'){
		mouseOver = mouseOverOnRow;
	}
	$("table.ms-listviewtable").each(function(){
	
		var thisListView = $(this);
		// Find colindex of YesNo-field
		thisListView.find(".ms-viewheadertr th").each(function(){				
			fName = $(this).find('div:first').attr('name')
			if(fName==fin){
				colIndex = this.cellIndex;
			}
		});
		// Loop trough all rows and highlight matched rows
		thisListView.find("tbody:not([id^='aggr']) tr:has(td.ms-vb2)[highlighted!='1']").each(function(){
			var rowVal = $(this).find(">td:eq("+colIndex+")").text();
			if(rowVal==valToFind){
				$(this).attr({'highlighted':'1','title':mouseOver}).css({'background-color':bgColor});
			}
		});
	});
}

function customTimeoutLoop(id){
var obj = $("#"+id);
var isloaded = ($(obj).attr('isloaded')=='true')?true:false;
	if(!isloaded){
		$(obj).hide();
		setTimeout(function(){
			customTimeoutLoop(id);
		},10);
	}else{
		$(obj).show();
		highlightRowByYesNoField();		
	}
}

function ExpGroupRenderData(d, a, e) {
    ULSA13: {
    }
    var c = document.getElementById("tbod" + a + "_"), b = document.createElement("DIV"), f = a.split("-");
    b.innerHTML = "<TABLE><TBODY id="tbod" + a + "_" isLoaded="" + e + "">" + d + "</TBODY></TABLE>";
    c.parentNode.replaceChild(b.firstChild.firstChild, c); 
 customTimeoutLoop("tbod" + a + "_");   
}

Save the code as a file named “HighlightRowByYesNoColumn.js” – mind the file extension, and upload to the scriptlibrary as shown above.

Note when combining with other scripts that embeds the function “ExpGroupRenderData”: The function “ExpGroupRenderData” is not to be added twice. You must leave the one in the script called last, and include the function call to both/all custom function that is to be triggered by expanding grouped view’s – like in line 58 in the SP2007-code above.

Ask if something is unclear

Regards
Alexander