Using Javascript to Manipulate a List Form Field

Using Javascript to Manipulate a List Form Field

Rate This

Hi, my name is Rob Howard, and I’m a Program Manager with the SharePoint Designer team. Like several of the other people posting here, I also built many of the Application Templates for Windows SharePoint Services.

If you’re familiar with them, you may have noticed that in several of the application templates we use a bit of Javascript to set default form values based on the query string. Because we found this to be useful in many different cases throughout our applications, I wanted to share our method with you guys so that you can include it in the applications you develop.

When might you use this?

It’s pretty easy to set a field’s default value through the list settings in the browser UI, so why might you need Javascript to set a default field value? The reason is that field default values can only take static values or simple formulae based on the current user or today’s date. If that meets your needs, then I’d definitely recommend sticking with that method. Sometimes, though, you may want the form to fill with default values based on the user’s interaction with the previous page, and that’s exactly where this method comes in.

How does it work?

In short, we add some Javascript to the page that runs when the body is loaded. This Javascript parses the page’s query string, locates the HTML objects that are rendered by the relevant SharePoint fields, and sets their value based on the information in the query string.

getTagFromIdentifierAndTitle

The most important part of our solution is the “getTagFromIdentifier” function. This function finds the HTML element rendered by a given SharePoint FormField control. It takes the following parameters:

  • tagName – The name of the tag rendered in the form’s HTML
  • identifier – The string associated with the SharePoint type of the relevant field
  • title – The value of the relevant HTML tag’s “title” attribute, which also matches the field’s display name

Here’s a partial table of SharePoint column types and their corresponding “identifiers” and “tagNames”:

SharePoint Field Type identifier tagName
Single Line of Text TextField input
Multiple Lines of Text TextField input
Number TextField input
Currency TextField input
Choice (dropdown) DropDownChoice select
Lookup (single)* Lookup select
Lookup (multiple) SelectCandidate; SelectResult select
Yes/No BooleanField input

*Lookups are a bit more complicated because Lookup FormFields render differently when the target list contains more than 20 items. See the end of the post for an example.

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;

}

fillDefaultValues

Now that we have the HTML elements that we want to set, we need the values with which to set them. In our solution, we wrote the “fillDefaultValues” function, which parses the page’s querystring and then uses the values to set the field defaults.

function fillDefaultValues() {

  var qs = location.search.substring(1, location.search.length);

  var args = qs.split("&");

  var vals = 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(' ');

    vals[nameVal[0]] = nameVal[1];

  } 

  // Set HTML element default values here

}

_spBodyOnLoadFunctionNames

In most cases SharePoint pages are based on a master page that contains the “body” element. These content pages can’t directly add a function to the body’s onload event. In order to work around this limitation, SharePoint provides the “_spBodyOnLoadFunctionNames” array. When the body is loaded, the onload event handler executes each function whose name is contained in this array. We added “fillDefaultValues” to the array so that it would run when the body’s onload event fires.

_spBodyOnLoadFunctionNames.push("fillDefaultValues");

All Together Now

With the script above, you can set most different field types to any value from the querystring – or any other source that javascript can access. Below is a full example of the script we use to set the default value of a Lookup field based on an ID stored in the querystring. You’ll notice that setting a Lookup field is a bit more complicated than some other field types. The reason is that Lookup FormFields are rendered with different HTML when the target list contains more than 20 items.

Enjoy!

<script type="text/javascript">

 

// This javascript sets the default value of a lookup field identified

// by <<FIELD DISPLAY NAME>> to the value stored in the querysting variable

// identified by <<QUERYSTRING VARIABLE NAME>>

 

 

// Customize this javascript by replacing <<FIELD DISPLAY NAME>> and

// <<QUERYSTRING VARIABLE NAME>> with appropriate values.

// Then just paste it into NewForm.aspx inside PlaceHolderMain

 

_spBodyOnLoadFunctionNames.push("fillDefaultValues");

 

function fillDefaultValues() {

  var qs = location.search.substring(1, location.search.length);

  var args = qs.split("&");

  var vals = 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(' ');

    vals[nameVal[0]] = nameVal[1];

  } 

  setLookupFromFieldName("<<FIELD DISPLAY NAME>>", vals["<<QUERYSTRING VARIABLE NAME>>"]);

}

 

function setLookupFromFieldName(fieldName, value) {

  if (value == undefined) return;

  var theSelect = getTagFromIdentifierAndTitle("select","Lookup",fieldName);

 

// if theSelect is null, it means that the target list has more than

// 20 items, and the Lookup is being rendered with an input element

 

  if (theSelect == null) {

    var theInput = getTagFromIdentifierAndTitle("input","",fieldName);

    ShowDropdown(theInput.id); //this function is provided by SharePoint

    var opt=document.getElementById(theInput.opt);

    setSelectedOption(opt, value);

    OptLoseFocus(opt); //this function is provided by SharePoint

  } else {

    setSelectedOption(theSelect, value);

  }

}

 

function setSelectedOption(select, value) {

  var opts = select.options;

  var l = opts.length;

  if (select == null) return;

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

    if (opts[i].value == value) {

      select.selectedIndex = i;

      return true;

    }

  }

  return false;

}

 

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;

}

</script>

  • I struggled with the prepopulating of Lookups until I realized the above code is designed to work on the ID of the Lookup Field. I was passing the value displayed in the lookup field and nothing worked.

    If you don't have the ID of the lookup field but you do have the text simply change

    the Line    if (opts[i].value == value) {  in the setSelectedOption to

       if (opts[i].innerText== value) {

    Good Post!

  • Anyone can help?

    Currently, i'm developing one page which is containt drop down list and i would like to select one of the values when the page is loading.

    Example:

    dropdown list has three values:-

    Waiting (this is the first value when the page is loading)

    Approve

    Reject

    Now, i would like to select the second value which is "Approve" when the page is loading.

    So, the "Approve" will be selected after the page is load.

  • 觉得这篇文章比较有参考价值,把大意翻译过来,没有忠实于原文。 原文链接:http://blogs.msdn.com/sharepointdesigner/archive/2007/06/13/u...

  • It looks like at least one person has been able to make this work for fields in the Insert Template.  I would appreciate some ideas on how to make this work on my page with two web parts with Insert Templates.  To clarify, the javasicript code fails on page load (throwing some annoying javascript errors)...then when the Insert Template is initiated on one web part, the code does run again and still gives the same error.  If I initiate the second Insert Template link, the script works fine and adds the default values to each Insert Template. So, I know what the problem is, I just don't know how to fix it.

    It doesn't seem that the FillDefaultValues script can run on page load in my scenerio, and I believe I'll have to have two seperate functions (one for each Insert Template on the page).  But, when and how can the function be called?  Ideally it would be called when I click 'Add' to initiate the Insert Template...  If anyone knows how to do that, please fill me in...

    Thanks

  • [SPD Workflows] Manipolazione JS e validazione di custom Collect Data forms

  • How to set the current user in a people picker field on the newform.aspx

  • this is very good solution and thanks you very match....

    but i have  a question.. If i want to set the selected value in a combo (lookup)  and i have 500 items or more what it happens with the time that you need to make the sequential search? Is there any faster way?

    again i want to thanks you for your solution

    Greek developer

  • Can anyone please tell me how can I have the current user as the default value in the Attendee2 field when the form is displayed in edit mode.

    <SharePoint:FormField runat="server" id="ff3{$Pos}" ControlMode="New" FieldName="Attendee2" __designer:bind="{ddwrt:DataBind('i',concat('ff3',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Attendee2')}" />

  • Can someone tell me how to use JavaScript with a multiple select lookup, I already got it working with the single lookup field. But when I change Lookup for SelectCandidate or SelectResult it doesn't works.

    Thans,

    Ronald

  • Siguiendo con la serie de post de construcción de aplicaciones de SharePoint utilizando SharePoint Designer

  • how can i make this work in Sharepoint portal 2003...

    i am not able to find the mainplaceholder tag there...(in code view FrontPage03)

    please help me...its really urgent!!!!!!!!!

  • I've noticed a lot of people struggling to set a people picker fields value to the current user.  I had the need to this today and have posted a solution on my blog.

    http://blogs.vbcity.com/skullcrusher/archive/2008/04/10/9024.aspx

    Hope this helps others

  • hi friends

    I have to pull query strings to my survey, i have successfully done it and i have to hide those controls and the question to the user can any one help me out for the javascript

  • Hi, here is a function for you to get the value from a lookup field by field name, a compliment to the function setLookupFromFieldName:

    function getLookupValueFromFieldName(fieldName) {

     var value;

     var theSelect = getTagFromIdentifierAndTitle("select","Lookup",fieldName);

    // if theSelect is null, it means that the target list has more than

    // 20 items, and the Lookup is being rendered with an input element

     if (theSelect == null) {

       var theInput = getTagFromIdentifierAndTitle("input","",fieldName);

    value = theInput.value;

     } else {

    value = theSelect.options(theSelect.selectedIndex).innerText;

     }

     return value;

    }

  • Hi

    I was wondering if anyone knows how to edit/append the query string that the ok button on a Document Upload.aspx page is creating.

    I am trying to set a drop down field on the EditForm.aspx page after a user selects a document.

    I already have what I need passed in the query string to the Upload.aspx page but I am unsure on how to go about pushing what I need from there to the EditForm.aspx page when the "ok" button is clicked.

    Thanks

Page 5 of 12 (167 items) «34567»
Leave a Comment
  • Please add 7 and 7 and type the answer here:
  • Post