Refferencing SharePoint form fields with JavaScript

July 17th, 2007 | Categories: SharePoint, SharePoint administration

Sometimes you need to refference SharePoint form fields for manipulation. I usually use JavaScript. With SharePoint 2.0 you can refference a form field with

document.getElementsByName(urn:schemas-microsoft-com:office:office#Field_Name)[0]

where Field_Name is the SharePoint name of the field (you can find it at the end of URL when viewing properties of the field under “Modify Settings and columns”. For example if I’d need to change the value of a form field Title, I’d use the following code:

document.getElementsByName(‘urn:schemas-microsoft-com:office:office#Title’)[0].value = ‘Boris’

Thus changing the value to Boris.

The story gets a bit more complicated with SharePoint 3.0. The names of fields now also contain ID of the form, which is constantly changing. The previous case in one of our forms would be

document.getElementsByName(‘ctl00$m$g_740df035_0c04_4906_89d7_cb38429413df$ctl00$ctl04$ctl00$ctl00$ctl00$ctl04$ctl00$ctl00$TextField’)[0].value = ‘Boris’

The problem occurs with changing ID of the form so you can’t (at least that I know of) refference the form field value by name alone.

The solution here is using form titles. I’ve prepared a small javascript to get the form field by its type and title.

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]
        }
    }
}

Using this script now you can change the value of a title field with

getField(‘input’,’Title’).value = ‘Boris’