Using the Signature Pad jQuery Plugin with SharePoint & InfoPath

Have you ever needed to capture signatures in SharePoint forms? What about InfoPath forms? I’m betting many people have seen a need to do this but have balked at the cost or complexity of the available solutions.

A client of mine named Cody Sellers (@codyjsellers), who works for Mercom Corporation had just such a need. Mercom is a smallish company that didn’t want to spend tens of thousands of dollars on a “real” eSig solution. Cody did some research and found a great jQuery plugin and turned to me for help implementing it. In this case we’re working with SharePoint 2013 on premises, but this should work with any version of SharePoint with some modification.

2014-06-18_13-38-20

The Signature Pad plugin comes from a clearly smart guy named Thomas J Bradley. Based on the work I’ve done with it so far, it’s well written with good documentation. Even better: it just plain works.

Signature Pad: A jQuery plugin for assisting in the creation of an HTML5 canvas based signature pad. Records the drawn signature in JSON for later regeneration.

The plugin allows you to capture signatures based on typed or drawn input and can be saved as JSON or a PNG image.

In our case, we wanted to be able to add a signature block at the bottom of multiple InfoPath forms. To make this work well, we decided that we would add the script into the master page. Yes, that may seen foolhardy, but a large majority of the work that is going to be happening in this Site Collection is filling out these forms.

Because of this, we needed a clear convention to follow in every form so that we could locate all of the signature fields (some forms have more than one) and add the signature pad capability reliably.

One of the hardest things about working with InfoPath forms client-side is that there are almost no sensible hooks in the emitted DOM. Everything is a .NET-like element id, like

ctl00_ctl33_g_3782ce51_9259_4854_80a0_e6355e54b690_FormControl0_V1_I1_T6

Since those ids can change anytime you change the form, you really want to give yourself something more solid to hook into. (At least we know that InfoPath won’t change anymore and the basic form elements are constant!)

To ensure that we could easily add the signature pad to any existing signature fields, we wrapped each signature field in an InfoPath section with its ScreenTip set to “==Signature==”.

InfoPath section with its ScreenTip set to ==Signature==

InfoPath section with its ScreenTip set to ==Signature==

The logic works like this:

  • Check to see if there’s a div with its id ending in ‘XmlFormView’ – this is the container for an InfoPath form. If there isn’t one, do nothing.
  • Find sections in the form that have their ScreenTip set to “==Signature==”. Sections have a fieldset container, and the title is set to the ScreenTip value. In other words, any section with its ScreenTip set to “==Signature==” will be treated as a signature area by the code.
  • Find the input element inside that section. This is the field where we want to store the JSON representation of the signature.
  • If the input element has no value, render the signature pad for signing (new forms)
  • If the input element already has a value, show the signature it contains (edit and display forms)

We decided to store the JSON representation of the signature in a field in each InfoPath form. Since the JSON represents the vectors from an HTML5 canvas, it’s a nice, standard way to store it. Images would require some separate repository or further encoding to be stored in a text field. Since the plugin can both emit and reconstitute the JSON into a signature, it’s a good way to go.

We ended up with the code below for the simplest case. (It’ll get more complicated as we get into the business rules, but this post is about the technology to capture and display the signatures.) When we create a new item in the newifs.aspx form, the Signature column will be empty and thus we will show the signature pad. If there’s already a value in the field, then we’re on the edit or display form, and signing has already happened so we just display the signature we have.

I’ve added comments that hopefully make the code simple enough to follow. As with all code you read on the Web, this isn’t just a drop-it-in-and-it’ll-work thing – you’ll end up tailoring it for sure. (One would think I wouldn’t need these caveats, but…)

$(document).ready(function() {
    // Find the guts of the InfoPath form in the page
    var infoPathContainer = $("div[id$='XmlFormView']");
    // if there's no InfoPath form, then we have nothing to do here (escape early)
    if (infoPathContainer.length !== 0) {
        setupSignatures(infoPathContainer);
    }
});
// There's an InfoPath form in the page, so look for signature fields and set them up
function setupSignatures(infoPathContainer) {
    // The Signature "signature" in the form. This makes it easy to select the proper form elements
    var signatureSignature = "==Signature==";
    // The signature field should be inside a section with its tooltip=signatureSignature
    var signatureContainer = infoPathContainer.find("fieldset[title='" + signatureSignature + "']");
    // The Signature field is the lone input element in the section
    var signatureBox = signatureContainer.find("input");
    // We may have multiple signature fields in the form
    signatureBox.each(function() {
        var thisSignatureBox = $(this);
        // We need a reference to the fieldset which represents the section several times
        var thisSignatureFieldset = thisSignatureBox.closest("fieldset");
        // Clean up the display by hiding the field we're using to store the JSON
        thisSignatureBox.hide();
        // The signature data is the value of the signatureBox
        var signatureData = thisSignatureBox.val();
        // If there's no signature yet...
        if (signatureData === "") {
            // Add the appropriate markup to the page
            thisSignatureBox.before(buildSignatureBox());
            // Bind to the click event for the 'Ready to Sign' button
            thisSignatureFieldset.find(".signature-ready").click(function() {
                $(this).toggle();
                $(this).next("div").toggle();
            });
            // Activate the signature pad in drawOnly mode
            var signatureArea = thisSignatureFieldset.find(".signature-box").signaturePad({
                drawOnly: true,
                lineTop: 125,
                output: thisSignatureBox,
                onBeforeValidate: function(context, settings) {
                    thisSignatureBox.focus(); // Needed to fire the change events bound to the field
                    thisSignatureBox.blur(); // Needed to fire the change events bound to the field
                    thisSignatureBox.hide(); // In case it becomes visible again
                }
            });
            // When the user clicks the button below the signature pad, validate
            thisSignatureFieldset.find(".signature-done").click(function() {
                thisSignatureFieldset.find("p.error").remove();
                signatureArea.validateForm();
            });
            // If we already have signature data, just show the existing signature
        } else {
            // Add the appropriate markup to the page
            thisSignatureBox.before(buildSignatureDisplay());
            // Activate the signature pad in displayOnly mode
            thisSignatureFieldset.find(".sigPad").signaturePad({
                displayOnly: true
            }).regenerate(signatureData);
        }
    });
}
// Function to emit the markup for the signature pad in signing mode
function buildSignatureBox() {
    var signatureBox = "<div class='signature-box'>" +
        "<input class='signature-ready' type='button' value='Ready to sign'/>" +
        "<div style='display:none;'>" +
        "<ul class='sigNav'>" +
        "<li class='drawIt'><a href='#draw-it'>Sign Here</a></li>" +
        "<li class='clearButton'><a href='#clear'>Clear</a></li>" +
        "</ul>" +
        "<div class='sig sigWrapper'>" +
        "<canvas class='pad' width='700' height='150'></canvas>" +
        "<input type='hidden' name='output' class='output'>" +
        "</div>" +
        "<input class='signature-done' type='button' value='Capture signature'/>" +
        "</div>" +
        "</div>";
    return signatureBox;
}
// Function to emit the markup for the signature pad in display mode
function buildSignatureDisplay() {
    var signatureDisplay = "<div class='sigPad signed'>" +
        "<div class='sigWrapper'>" +
        "<canvas width='700' height='150' class='pad'></canvas>" +
        "</div>" +
        "</div>";
    return signatureDisplay;
}

Here are some screenshots from our proof of concept:

The form when it loads

The form when it loads

Ready to sign

Ready to sign

Signed

Signed

Signature displayed on the display form

Signature displayed on the display form

Snippet of the data that is stored for a signature

Snippet of the data that is stored for a signature

SharePoint List Settings Issue: “Internet Explorer is required to use this feature.”

This one belongs firmly in the “things that make you go hmm…” department.

Let’s say you are a good do-be like me and you use all of the Microsoft products that you can get your hands on. You’ve got email and SharePoint running on Office 365, you use all the Office applications and tools, you’re up to date on your version of Internet Explorer… You get the picture.

Well, sometimes all that good behavior doesn’t pay. Today I wanted to edit an InfoPath form attached to a list in SharePoint 2013 on premises. (You won’t run into this problem on Office365, at least it doesn’t happen in my tenant. Office365 seems to know IE11.) I went to the List Settings and clicked on the Form Settings link. I’m using Internet Explorer 11, so I’m as up to date as I can be without getting into beta territory.

Lo and behold:

Internet Explorer is required to use this feature.

Internet Explorer is required to use this feature.

Yup. I’m using Internet Explorer and the message says “Internet Explorer is required to use this feature.” The issue is that the on premises install that I’m working with doesn’t understand Internet Explorer 11. It *should* see it as Internet Explorer, though, and give me a better message. I’m not exactly sure what patch level we’re on, but I think it’s pretty close to current.

Fortunately, there is an easy fix for this. Simply hit F12 to bring up the Developer Tools and scroll all the way down to the bottom of the left side icon list.The one you want to click on looks like this:

Emulation

That will give you access to the Emulation settings. Change the User agent string setting to Internet Explorer 10.

2014-06-18_10-21-10

Fixing the issue by changing the User agent string

The page will reload and now SharePoint will understand that you are the good do-be that you are, speaking IE10ish instead of IE11ish. After you do your work, it’s a good idea to switch back to default so that you are speaking IE11ish again.

The Emulation settings give you a bunch of other nice tools (want to act like an XBox360?), so if you have interest in testing things in different browsers types, etc., be sure to check out the rest of the settings as well.

Feminism in Tech – Be a Part of the Solution

My friend (and client) Dan Antion (@dantion) tweeted a link to an excellent article this morning entitled An Open Letter on Feminism In Tech. The subtitle is “We are tired of pretending this stuff doesn’t happen.” I’m right there with this.

My role models about feminism were my mother Christina Bellamy and my paternal Grandfather Denton (of all people!).
Mom and Me18800
Their type of feminism wasn’t the radical feminism of the early 70s with all of it’s harsh demands and in-your-face rhetoric. It was exactly the type of feminism described in this excellent article by a group of women technologists.

Feminism is not a dirty word. Feminism is the radical notion that women are people, and that we want to be treated as equals.

As more eloquently said in the article, we can’t allow the sorts of bad behavior that occur in tech, or anywhere else. In the article, the writers point out that these tenets should apply to *any* group within tech that isn’t the mainstream, white male group that has dominated the industry historically.

But it goes much further than that.

At our son Calder’s school they have a zero tolerance rule about bullying. It causes some uncomfortable moments, but the effect is virtually zero bullying, creating a nurturing, healthy learning environment. Here’s a Wordle that shows many of the words that describe what this leads to. Take out the obviously unaligned ones, and I’d say that this is how we should make tech feel to women, or anyone else.

Runkle Olweus

Each of us should be a part of the solution. In SharePointlandia (aka the SharePoint Community), we have far less of the bad behavior than what I’ve seen in other technologies. So on some levels, we’re lucky. Working with SharePoint to some degree means a sort of self-selection for people who see collaboration and group work as a useful, productive thing. The characteristics of who is a part of those activities becomes less important. But we aren’t perfect either.  There is always room for improvement and collective enlightenment. (Yeah, that sounds a little sappy, but even when you get really good at something, you can strive to be great.)

To borrow a phrase, “If you see something, say something”. Let’s make sure that SharePointlandia is a land of openness and opportunity for all of us, no matter who or what we are.

Addendum: I would be remiss if I didn’t mention Women in SharePoint, which “is dedicated to helping women working as SharePoint professionals reach their career objectives through a variety of community, training and mentoring programs.”

SPServices Stories #21 – Redirect If User Clicked a Button Previously

This entry is part 20 of 20 in the series SPServices Stories

Introduction

teylynIngeborg Hawighorst (@IngeborgNZ) is a long-time SPServices user who has come up with any number of intriguing uses for the library. I’d recommend her blog anytime if you’d like to learn about interesting things you can do with SharePoint, but even more so if Excel is your bag. Ingeborg has been an Excel MVP for years running (see her profile on the MVP site). Some of the best solutions using SPServices come out of discussions in various SharePoint-oriented forums. In this case, Ingeborg spotted some suggestions from Eric Alexander (@ejaya2 aka PirateEric) and decided to build it out. Without further ado, here is Ingoborg’s article, reposted from her blog cheers, teylyn.

Redirect If User Clicked a Button Previously

I just came across this question in sharepoint.stackexchange.com. When a user visits a SharePoint site, they are presented with a splash screen and need to accept the policy before they can proceed. Upon subsequent visits, the splash screen does not show, because SharePoint will remember the  user. PirateEric outlined a possible solution: Use a SharePoint list to save the user name when the button is clicked. When the page loads, look up the user in the list. If they already exist, redirect the page, if not, show the splash page with the button to accept the policy. If the policy changes and users need to be made aware of that, simply remove all items in the list that tracks the users. All this can be done with jQuery and web services. That intrigued me and I had a go at actually building this, using Marc Anderson’s SPServices.

How to set it up

Create a SharePoint custom list with two fields, Title and UserName. The former is the out of the box field, the latter is a simple text field. Create two pages, the Splash page with the button and the page that is the desired destination page for all visitors. In my sample these are called Splash.aspx and MainContent.aspx On the Splash page the code that you can see below will be loaded before any other web part. If you use a Content Editor Web Part to load the code with a content link, make sure that it’s the first web part on the page. In many cases, JavaScript and jQuery will be placed in the last web part of the page and run after the DOM has loaded. But in this case this would mean that the Splash page appears briefly, even if it is followed by a redirect to a different page. The Splash page provides the policy (or terms and conditions) that the user must accept, and a link or a button that the user can click to accept. This link or button must then trigger a JavaScript function. That is very easy to do. I used a button and put the html straight into a CEWP like this:

<button onclick="PolicyButtonClick()" type="submit">
   I accept the policy
</button>

So the user clicks the button and the JavaScript function PolicyButtonClick() will run. This function can be found in the code below. First, the jQuery library and the SPServices library are loaded. Then the user name of the current user is retrieved with the SPServices call using SPGetCurrentUser. It returns a text string in the format DOMAIN\Account.  Next, the SPServices call uses the GetListItem. In the call, a CAML query is constructed that will return only list items where the column UserName equals the current user.  The items returned by that query are then counted. Since the user account is a unique value, we can safely assume that the query will either return one result or no result at all. If the query returned an item, this means that the user has previously accepted the policy and the script will redirect to the MainContent.aspx page.  If the query did not return anything, the current page will continue to be displayed. When the user clicks the button to accept the policy,  the user name is written into a variable. Then the SPServices operation to UpdateListItem is called and will create a new item in the list “PolicyAccepted”, storing the previously established account name in the column UserName. Then the MainContent.aspx page is loaded. The next time the user opens the Splash page, their account name will be found in the PolicyAccepted list and they will not see the Splash page again, unless the entry in the list is deleted. Here is the complete script:

<script type="text/javascript" src="/path/jquery-1.10.2.min.js" language="javascript"></script><script type="text/javascript" src="/path/jquery.SPServices-2013.02a.min.js" language="javascript"></script><script type="text/javascript">// <![CDATA[
// start the code even before the DOM is loaded, so not waiting for document ready
//$(document).ready( function() {
// get the user name
 var userName= getUserName();
// find the user name in the list
 var userAccepted = matchUserName(userName);
 if (userAccepted == 1 )
 {
 // redirecting page
 window.location.replace("http://path/Documents/MainContent.aspx");
 }
//});

function getUserName() {
 var thisUserAccount= $().SPServices.SPGetCurrentUser({
 fieldName: "Name",
 debug: false
 });
 return(thisUserAccount);
}

function createNewItem(theTitle, theUser) {
 $().SPServices({
 operation: "UpdateListItems",
 async: false,
 batchCmd: "New",
 listName: "PolicyAccepted",
 valuepairs: [["Title", theTitle], ["UserName", theUser]],
 completefunc: function(xData, Status) {
 }
 });
}

function matchUserName(userName) {
 var queryText = "<Query><Where><Eq><FieldRef Name='UserName'/><Value Type='Text'>" + userName + "</Value></Eq></Where></Query>";
 $().SPServices({
 operation: "GetListItems",
 listName: "PolicyAccepted",
 async: false,
 CAMLQuery: queryText,
 completefunc: function (xData, status) {
 itemCount = $(xData.responseXML.xml).find("rs\\:data, data").attr("ItemCount");
 }
 });
 return(itemCount);
}

function PolicyButtonClick() {
 var userName= getUserName();
 var theTitle= "Accepted";
 createNewItem(theTitle, userName);
 window.location.href = "http://path/Documents/MainContent.aspx";
}
// ]]></script>

Announcing the Top 25 SharePoint Influencers for 2014

HomeLast Wednesday at the Microsoft SharePoint Conference in Las Vegas – in a clear lapse of judgment – harmon.ie named me the seventh most influential SharePoint person for 2014. Read more in Announcing the Top 25 SharePoint Influencers for 2014 on the harmon.ie blog.

I’m honored and humbled to be recognized as even in the same league as the other 24 people on the list. They are some of the smartest and most dedicated people in the SharePoint community. I hardly belong there with them. Thanks to harmon.ie for the recognition. Thanks also to anyone out there who finds my musings and activities useful and voted for me for this honor.

The Top 10

  • Andrew Connell, Co-Founder, Co-Host, Microsoft Cloud Show (@andrewconnell).
  • Joel Oleson, Global Collaboration Evangelist, Community Builder and Strategist (@joeloleson).
  • Todd Klindt, SharePoint Consultant, Rackspace Hosting (@toddklindt).
  • Christian Buckley, Chief Evangelist, Metalogix (@buckleyplanet).
  • Laura Rogers, Senior SharePoint Consultant, Rackspace Hosting (@WonderLaura).
  • Jeremy Thake, VP of Global Product Innovation, AvePoint Inc. (@jthake).
  • Marc D. Anderson, Management and Technology Consultant, Sympraxis Consulting LLC (@sympmarc).
  • Dux Raymond Sy, VP of Customer Strategy & Solutions, AvePoint Public Sector (@meetdux).
  • Jeff Willinger, Director of Collaboration, Social Business and Intranets, Rightpoint, World-wide SharePoint Speaker and Evangelist (@jwillie).
  • Spencer Harbar, Managing Director, Triumph Media Limited, Enterprise Architect, Microsoft (@harbars)

As a service to the business community, harmon.ie has commissioned the third annual ranking of the “Top 25 SharePoint Influencers.”  Prominent industry analyst Dana Gartner and Scratch Marketing + Media were tapped to identify those leaders who are helping others navigate the SharePoint/Yammer platform. Based on a finalist list of top 100 SharePoint professionals, a weighted formula was used to identify the top 25 U.S. SharePoint influencers. Selection was based on: each professional’s SharePoint knowledge and business impact; digital and social presence and influence; blog reach and frequency; depth of SharePoint topic coverage; citations by other influential bloggers; and more than 3,000 qualified community votes.