Monday, March 8, 2010

Adding JavaScript to SharePoint Form Field


Many time in my current project I felt the need of adding javascript to the SharePoint Form Fields to trigger my custom function in order to perform some calculation and other stuff.
Luckily I found the following blog and it sloved my Javascript problem.

URL: http://webborg.blogspot.com/2008/04/add-functions-and-events-to-sharepoint.html

When you add the javascript mentioned in the above blog in the bottom of your page, do call your custom function again at the end because if ur page postbacks and reload (due to some missing required field or any other reason) dropdown change event wont fire. So here is the updated code:

function getField(fieldType,fieldTitle) { 
    var docTags = document.getElementsByTagName(fieldType); 
    for (var i=0; i < docTags.length; i++) { 
        if (docTags[i].title == fieldTitle) { 
            return docTags[i] 
        } 
    } 
} 
 
function DisplayMessage()
{
 alert('Hello World');
}

//Add JavaScript to Decision Column
getField('select','Decision').onchange = function() {DisplayMessage()};

//Add additional call
DisplayMessage();
Line 19 is the additional call to the function.
Above code will add onchange event to choice type SharePoint field and each time the selected value is changed, DisplayMessage() will be triggered.