Tuesday, September 8, 2009

Using JQuery (client side JavaScript) to handle an ‘All’ option for SharePoint (edit)form checkboxes

Sometimes there are easy solutions to easy problems. All it takes is a little thinking outside of the box.

Prerequisites/knowledge:

SharePoint: Intermediate
HTML: Advanced
JavaScript: Intermediate/advanced
.Net: None
Scenario:
In a SharePoint entry form the user can select multiple values from a list. This should include an “All” option so in a long list the user can select or de-select all values with one click.

So the interface should look like:
Give this functional design to a SharePoint developer and he/she will come up with either:

This is not possible with SharePoint
This requires developing a new field control
I’ll handle this server-side

Another approach
Let’s take a step back, forget SharePoint and just summarize what actions needs to happen (as if you instructed another human being to perform those actions)

When the All option is clicked do:

Is the All option checked?
Then check all other checkboxes
Else uncheck all other checkboxes
That’s all!

So put on your SharePoint cap again.
These actions need to happen client-side (inside the browser).

We want to attach a click handler to the All checkbox and when clicked it should toggle all the other checkboxes. (Note to self: there can be multiple groups of checkboxes on an entry form)

If you have HTML & JavaScript experience you’re still with me and probably already thinking of a technical solution. Yes we need the _SPBodyOnloadWrapper here. And when you have (more then) some DOM experience you can attach code to the HTML INPUT tags.

We’ll care about the How later. First lets analyze the HTML code SharePoint delivers and see how the checkboxes are defined.

Let’s view the source of the entry/edit form.

The HTML code Sharepoint generates


I tidied the HTML a bit. As you can see every (input) checkbox has a unique id. We can fairly assume that SharePoint generates these so we can’t use hardcoded IDs. Now we need to come up with an approach to ‘execute’ Step 1

“Then check all other checkboxes”

Note that the IDs are all sequentially numbered; so apart from the last 2 digits all IDs (within one group) are the same.

Basically we want to extend the INPUT tag of the All option with an extra JavaScript function



The DOM battle plan:
The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page.

So with the DOM INPUT element for the All option we want to:

IF an All option is clicked we want to:
execute JavaScript code which:

takes the ID of the clicked option

cuts of the last 2 digits

Uses that ID to toggle the other DOM elements.

If you’re a programmer you’re already seeing the complex JavaScript manipulation of HTML DOM elements this takes.

If you are not a programmer you probably don’t have a clue what I’m talking about… but do read on!

Enter JQuery
jQuery is a JavaScript library that helps you keep your code simple and succinct by addressing some of the complexities of Document Object Model (DOM) scripting and Ajax interaction. It helps you get right to the point and express yourself in the fewest possible characters and was initially created by John Resig in early 2006. It comes as a single JavaScript file with optional plugins containing all the common DOM, Event, Effects, and Ajax functions.

With JQuery the JavaScript we have to add to the SharePoint page:

$(”.ms-RadioText[title=’All’] :checkbox”).click(function(){
var otherids = (this.id).substring(0, (this.id).length-2 );
$(”input[id^=’”+otherids+”‘]”).attr( “checked” , (this.checked)?”checked”:”" );
});

YES! That’s all it requires. Sometimes a solution is as simple as the problem. Provided you use the right tools.

This requires the JQuery JavaScript library. But I’m sure you can come up with similar code using MooTools or Sciptalicious. BTW the JQuery library is also used by Google and many other major sites.

It’s (compressed) footprint is only 20k; compare that to the xxxK Microsoft SharePoint itsef loads in various supporting JavaScript libraries and you have to agree it’s a minimal but o so valuable extension to your SharePoint environment.

Step by step
$(”.ms-RadioText[title=’All’] :checkbox”).click(function(){

JQuery selection of DOM objects which apply to the rules:

Is class ms-Radiotext

Which:

Have the tile attribute ‘All’

Which:

Are of type: checkbox

A function is attached to the Click event:

var otherids = (this.id).substring(0, (this.id).length-2 );

chops off the last 2 digits of the clicked (=this) identifier.

$(”input[id^=’”+otherids+”‘]”).attr( “checked” , (this.checked)?”checked”:”" );

The key here is the ^=

This Jquery statement matches all DOM input elements which id attribute start with the given id

It then sets the attribute “checked” to either “checked” or an empty string

});

Closes the function.

Using it in SharePoint
[to be extended]

Add the JQuery.js library to a document library. Note the complte path to it
Create a custom List ‘Vistted Continents’
Create a column ‘continents’ with the values (including ‘All’)
Open a New entry for the list
Add a Content Editor WebPart to the NewForm page (how to: see Adding WebParts to Form pages (to be written))
See: Google: ToolpaneView=2
Paste in the code


//Script Highlighter: http://tohtml.com/jScript/
(The whole JQeury initialisation code can be placed in a MasterPage; that would bring the CEWP code to just the 3 lines of code)

Additional notes:
A SharePoint choice field can only store 255 characters; so the user gets a warning/error when the total number of characters for all selected values exceeds 255 characters!
Must read JQuery references
JQuery homepage
http://www.jquery.com/
Good examples can be found on other sites:

JQuery (chainable events) examples
http://codylindley.com/blogstuff/js/jquery/
Simple JQuery examples
http://markc.renta.net/jquery/
50+ JQuery examples
http://www.noupe.com/jquery/50-amazing-jquery-examples-part1.html
45 even cooler examples
http://outatime.wordpress.com/2008/03/06/45-fresh-out-of-the-oven-jquery-plugins/
Rule library – manipulating CSS attributes
http://flesler.webs.com/jQuery.Rule/

No comments: