Monday, February 11, 2013

SharePoint 2010: Set default values in list form fields using javascript.

SharePoint 2010 provides out of the box functionality to set default values in fields of any list form through list settings but there are some limitations regarding this option. These values are either static or simple formula based with logged-in user and today's date variation and we also cannot select default values for lookup fields. Sometimes you need to set default values to the form fields which are dynamic or on demand, like values from query string, based on any status field or select lookup field by value or text.

This post is all about a simple solution to set default values in list forms using some javascript. Javascript methods here parses page's HTML objects, locates required field and sets default values to the field.

Following are some javascript functions used for this purpose:

1. GetTagFromIdentifierAndTitle

function GetTagFromIdentifierAndTitle(tagName, identifier, title) {
         var idLength = identifier.length;
         var tags = document.getElementsByTagName(tagName);
         for (var i=0; i < tags.length; i++) {
              var tagID = tags[i].id;             
              if (tags[i].title == title && (identifier == "" || tagID.indexOf(identifier) == tagID.length - idLength)) {
                   return tags[i];
              }
          }
          return null;
    }


This is the key function for this solution. This functions locates HTML object  of a form field on the page. It takes three parameters:
  • tagName: Name of the form field's HTML tag.
  • identifier: type of the form field. (optional parameter, empty string "" can also be used)
  • title: Title of the form field, mostly it is the display name of the field
i) For single line of text, number, currency and yes/no:
   tagName: input
   identifier: BooleanField for yes/no field and TextField for others.

ii) For multiple line of text:
   tagName: textarea (for simple text not for rich text)
   identifier: TextField

iii) For lookup:
   tagName: select
   identifier: lookup

2. SetLookupFromFieldName and SetSelectedOption

function SetLookupFromFieldName(fieldName, value) {
         if (value == undefined) return;
         var theSelect = GetTagFromIdentifierAndTitle("select","Lookup",fieldName);

         if (theSelect == null) {
              var theInput = GetTagFromIdentifierAndTitle("input","",fieldName);             
              document.getElementById(theInput.optHid).value = value;             
         } 

        else {
              SetSelectedOption(theSelect, value);
         }
    }


    function SetSelectedOption(select, value) {
         var opts = select.options;
         var optLength = opts.length;
         if (select == null) return;

         for (var i=0; i < optLength; i++) {

              if (opts[i].value == value) {
                   select.selectedIndex = i;
                   return true;
             }
        }
         return false;
    }


These two functions can be used to set lookup fields based on value property. 
  • fieldName: Title or display name of the form field.
  • value: Value of the option needs to be selected as default.

3. SetLookupFromFieldNameByText and SetSelectedOptionByText:

function SetLookupFromFieldNameByText(fieldName, text) {
    try
    {
         if (text == undefined) return;
         var theSelect = GetTagFromIdentifierAndTitle("select","Lookup",fieldName);

         if (theSelect == null) {
              var theInput = GetTagFromIdentifierAndTitle("input","",fieldName);
              ShowDropdown(theInput.id);
              var opt=document.getElementById(theInput.opt);
              SetSelectedOptionByText(opt, text);
              OptLoseFocus(opt);
         } 

         else {
              SetSelectedOptionByText(theSelect, text);
         }
    }
    catch(ex)
    {
    }
    }
   
    function SetSelectedOptionByText(select, text) {

         var opts = select.options;
         var optLength = opts.length;
         if (select == null) return;

         for (var i=0; i < optLength; i++) {

              if (opts[i].text == text) {
                   select.selectedIndex = i;
                   return true;
             }
        }
         return false;
    }


These two functions can be used to set lookup fields based on text property. 
  • fieldName: Title or display name of the form field.
  • text: Text of the option needs to be selected as default.

4. GetQueryStringValue:

    function GetQueryStringValue(variable)
    {
        var queryString = location.search.substring(1, location.search.length);
      
        var args = queryString.split("&");
        var queryStringValues = new Object();     
      
        for (var i=0; i < args.length; i++) {
            var nameVal = args[i].split("=");
            var temp = unescape(nameVal[1]).split('+');
            nameVal[1] = temp.join(' ');
            queryStringValues[nameVal[0]] = nameVal[1];
        }

        return queryStringValues[variable];
    } 


This function returns value from query string variable.


Usage:

Set default value in Title field of list form:
GetTagFromIdentifierAndTitle("input","","Title").value = "test default value for title";
 or
GetTagFromIdentifierAndTitle("input","TextField","Title").value = "test default value for title";

Set default value for the lookup field with display name "Category":
var lookupId =  GetQueryStringValue("lookupId");
SetLookupFromFieldName("Category", lookupId );

 var lookupText =  GetQueryStringValue("lookupText");
SetLookupFromFieldNameByText("Category", lookupText);

You can place all these functions in a Content Editor Web Part (CEWP) along with a function which sets/selects default values in form fields.

1 comment:

  1. Hey Raza,

    Great Post!
    Does this solution work in SharePoint 2007? I can't seem to get it to work :(

    Thanks,

    David

    ReplyDelete