Adding custom JavaScript to a SharePoint Form

March 15, 2009 · 0 comments

in Programming

Recently I was implementing a simple bug tracker in the form of a SharePoint list, and I wanted to add some simple JavaScript to the bug entry form that captured the referring page. This seemed like a simple enough feature, but as it turned out, using JavaScript within a SharePoint form isn’t exactly straight-forward.

First of all, you have to use a built-in JavaScript function to register the block of code that you want run. The name of the function I wrote was setReferrer, and the code to register my function looks like this:

_spBodyOnLoadFunctionNames.push("setReferrer");

The other problem I ran into was getting a handle on the referrer field that I wanted to set. In the SharePoint designer, the field looks like this:


Not exactly intuitive what the field is going to be named on the client side, is it? After a bit of searching around on Google, I found a fairly simple snippet of code to handle the work, which you’ll see below as the function getTagFromIdentifierAndTitle:

function setReferrer() {
    var referrer = getTagFromIdentifierAndTitle("input", "UrlFieldUrl", "Referring Page");
    if (document.referrer != "")
        referrer.value = document.referrer;
    else
        referrer.value = "http://";
}
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
    var len = identifier.length;
    var tags = document.getElementsByTagName(tagName);

    for (var i=0; i < tags.length; i++) {
        var tempString = tags[i].id;
        if (tags[i].title == title && (identifier == "" ||
            tempString.indexOf(identifier) == tempString.length - len))
            return tags[i];
    }
return null;
}

And with that, the code works beautifully. There are definitely a few “gotchas” to working with SharePoint, especially since the documentation is lacking in these areas. SharePoint works fairly well “out of the box”, but if you want to do any of your own customizations (even something as simple as I’ve done here), you definitely have to work for it. Hopefully I’ve been able to help save someone a headache or two.

Leave a Comment

Previous post:

Next post: