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>

  • This blog assumes you are familiar with techniques to add javascript to a SharePoint page (specifically

  • Can anyone suggest script for date comparison ? like there are two date fields i.e. start date and end date. I want to make sure that Enddata should not be less then start date.

  • Well I got the text fields and choice field to auto populate. But does anyone know the identifiers for the date fields?

  • ok, just figured it out...such a relief and just in time! If anyone else is interested here is the code for the Date Picker control and the Choice control :

    <script>

    function setChoiceFromFieldName(fieldName, value) {

     if (value == undefined) return;

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

     setSelectedOption(theSelect, value);

    }

    function setDateFromFieldName(fieldName, value) {

     if (value == undefined) return;

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

     theInput.value=value

    }

    // heres the mod that was posted earlier by lyndon

    // for lookup controls and choice controls to filter by the text values

    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].innerText == value) {

         select.selectedIndex = i;

         return true;

       }

     }

     return false;

    }

    </script>

  • I also desparately need to find a way of getting, then passing an ID to the newitem.aspx - but I have no idea what you people are talking about - so I will continue Googling until I find a blogger who will write about this on a 4th grade level.

  • How to update the drop down boxes of datetime filed using javascript? I need to add +5 to the current Hours..

  • Same question as above from Monty...  I've found this question on many other sites, but no posted answers.  

    ... 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.

  • Figured it out... it works for libraries just the same.  The upload.aspx passes the query string through.

  • Guys, as per other posts(RamUday) I've been having some trouble to select the "multiple lines" boxes as "input". Change to textarea and has worked well. Cheers.

  • I was breaking my head over how to populate the Hyperlink field with a default value using javascript

    About what its tag name and identifier could be.

    Well I now figured out and hope it would definitely help others.

    FOR Hyperlink Field

    Tag name- input  

    Identifier- URLFieldURL

    And just remember that if you are defaulting the Hyperlink field to a local link on the system.

    Replace "\" with "/"

    For ex: "\\pbosfile06\policy\Application" Change that to "//pbosfile06/policy/Application". It would now work fine without any problem.

    And we can use the same function mentioned in this blog getTagFromIdentifierAndTitle()

  • Hi,

    What is the tagname for a person/group?

    Thanks

    Chris

    sammutchris@hotmail.com

    sammutchris@gmail.com

  • Hi,

    I have a question about drop-down lists.  I am fairly new to sharepoint so please bear with me.  I have data form with a connection to SQL server 2000.  I have a table with multiple foreign keys.  Instead of displaying the foreign key (number), i want to display a drop down list for the name in that table.  Here is the example below:

    Table Mentor (m.ID, name, role, d.ID, p.ID)

    Table Division d(ID, division)

    Table Plant p(ID, plant)

    I want to display a data view form that i am able to insert, delete, and update.  I want the table to display m.name, m.role, d.division (drop down from existing data in division table), p.plant (drop down from existing data in plant table).

    Thanks in advance for the help,

    Bobby

  • Hello Rob,  I am getting a script error when I add the code to my page.  Any thoughts on this error?  

    Webpage Script Errors

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.590; Zune 2.0; InfoPath.2; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; MS-RTC LM 8; .NET CLR 3.5.30428; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; SPC 3.1 P1 Ta)

    Timestamp: Mon, 13 Oct 2008 16:02:43 UTC

    Message: 'undefined' is null or not an object

    Line: 2097

    Char: 2

    Code: 0

    URI: http://intranet/_layouts/1033/core.js?rev=S5dt4K8TJGVTYU9HrW6enw%3D%3D

    Message: Object doesn't support this property or method

    Line: 164

    Char: 1

    Code: 0

    URI: http://intranet/sites/main/ee/hotline/Page/Add%20Question.aspx?SectionTitle=06 WOOD, PLASTICS & COMPOSITES&CategoryTitle=ARCHITECTURAL WOODWORK

  • fty - That line in my core.css is:

    var rgopt=strOpts.split("|");

  • Hi,

    How would you manage to use the web part parameters past in from athet web part as the default value. How can the parameters be retrieved by javascript?

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