Setting SharePoint Form Fields Using JavaScript

In a few of my previous blog posts I have used JavaScript to set SharePoint form fields in NewForm.aspx.  Using JavaScript to set these fields comes in really handy whether you are setting fields based upon query string variables (see previous posts) or setting a field to some other value.

So, I’m going to quickly breakdown the JavaScript I used to set those fields and hopefully make it a little more understandable.  Again, I did not “come up” with this JavaScript.  I stole it from some of the site templates that Microsoft provides. 

Getting Query String Variables

If you happen to be passing values in your Query String that you want to use (see previous posts), you’ll need to parse them out to get their names and values. The following JavaScript loops through the Query String names and values and stores them in a hashMap using the name as the key.

//store the query string
var qs = location.search.substring(1, location.search.length);
//split query string by name value pairs
var args = qs.split("&");
var vals = new Object();

//loop through name value pairs and store
//in a hashmap using field name as key

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

Finding The Form Field to Set

Next, we need to write a function that finds the field we are wanting to set (or read) the value of. The following function can be used to return a specific field object based upon its type, identifier, and name.

//getTagFromIdetifierAndTitle
//Get form field by type & title
//parameters:  tagName:  type of tag to return (‘input’ & ‘select’ are the ones I use)
//             identifier:   Optional identifier of the tagName in question
//             title:         The specific title (name) of the field you would like to retrieve 
//returns:  field object to set or get value of (or do whatever you want I guess)
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 you are not sure what the actual title of your field is, uncomment this alert
          //alert(tags[i].title);
          if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
               return tags[i];
          }
      }
      return null;
}

Calling Methods To Set Various Field Types

Okay, now let’s put everything together and set a couple of form field values.  The code is slightly different depending on the type of field you are wanting to set/get.

Text Boxes

Below is the code for calling the above methods and setting a text box value.  This code assumes there is a query string variable named “status”.

var theTextBox = getTagFromIdentifierAndTitle("input","","status");
theTextBox.value = vals["status"];

Check Boxes

Check Box objects are retrieved the same as as text boxes.  Let’s say you want to find a check box field named “notify me” and set it as checked.

var theCheckBox = getTagFromIdentifierAndTitle("input","","notify me");
theCheckBox.checked = true;

Select Boxes

There’s a little more involved when setting the value of a select list.  First you need to find the select object, then you need to set the selected option.

When all is said and done and you create the following functions, you can set the value of a select as follows (let’s assume we have a drop down called “status” and we want to set its value to “active”).

setLookupFromFieldName(“status”,”active”);

//setLookupFromFieldName
//Sets the value of a select of a given name to the option of the given value
//parameters:  fieldName:  name of select to set
//             value:   option to set select to
//returns:  nada
function setLookupFromFieldName(fieldName, value) {
     if (value == undefined) return;
     var theSelect = getTagFromIdentifierAndTitle("select","Lookup",fieldName);
     //if the select wasn't found, try getting it as an 'input' type
     if (theSelect == null) {
          var theInput = getTagFromIdentifierAndTitle("input","",fieldName);
          ShowDropdown(theInput.id);
          var opt=document.getElementById(theInput.opt);
          setSelectedOption(opt, value);
          OptLoseFocus(opt);
     } else {
          setSelectedOption(theSelect, value);
     }
}

//setSelectedOption
//Set the value of a select to the given option
//parameters:  select:  Select object to set
//             value:  Value in options to set select to
//returns:  true if value was set, false if option could not be found to set value to
function setSelectedOption(select, value) {
     //get list of options
     var opts = select.options;
     var l = opts.length;
     if (select == null) return;
     //loop through all the options
     for (var i=0; i < l; i++) {
      //if the option is found that is the same as the value, set the value
          if (opts[i].value == value) {
               select.selectedIndex = i;
               return true;
     }
}
     return false;
}

That’s it… why… what were you expecting?

So, there you have it.  If you aren’t using JavaScript at all, hope this makes it a little less daunting when setting those field values.  Get comfortable with it, you’ll probably want to start using jQuery at some point.  :)

As always, your comments are always welcome.  This blog is for you guys. 

posted @ Monday, July 06, 2009 10:18 PM

Print

Comments on this entry:

# re: Setting SharePoint Form Fields Using JavaScript

Left by Steve French at 7/9/2009 10:12 AM
Gravatar
Hey Hillbilly! What's the best way to default a Person field to the currently logged in user? Many thanks!

# Inserting table rows in Editform with Javascirpt

Left by JCNET at 12/8/2009 4:26 PM
Gravatar
Thank you.

Somewhat Related.

I'm trying to insert some table rows in the middle of a List editform textboxes based on strings in the column name.

I have some javascript code that works great on a simple html page with a table but won't work when inserted into an editform.aspx.

We are able to change text in the cells and turn display off for select rows, but attempts to insert a new row does not work.


<script type="text/javascript">
var theRows = document.getElementsByTagName("TR");
var r = 0;
var strTitle = "";
while (r < theRows.length)
{ try
{ strTitle = theRows[r].innerText || theRows[r].textContent;
strTitle = strTitle.replace(/\n|\r|\t|\^ /g,"");
var row = theRows[r],
cells = row.getElementsByTagName('td');
if (cells[0].className.indexOf('ms-formlabel') > -1)
{
if (strTitle.indexOf("(HP)") == -1)
{
theRows[r].style.display = "none";
}
else
{

theRows[r].cells[0].innerHTML = theRows[r].cells[0].innerHTML.replace("(HP)","");

if(/H\:/.test(strTitle))
{
var fheader = (strTitle.match(/\(H\:(.*?)\)/g));
//var header = fheader.replace("(H:","").replace(")","");
var header = fheader;
newrow=document.createElement('tr');
newcell=document.createElement('td');
newcell.appendChild(document.createTextNode(header));
newrow.appendChild(newcell);
alert(header);
r.parentNode.insertBefore(newrow,r);
alert("Done");
}
}
}

}catch(err){}r+=1;
}
</script>


Google Search "SharePoint Inserting a table row"

# re: Setting SharePoint Form Fields Using JavaScript

Left by ally at 12/15/2009 3:43 AM
Gravatar
thank you

# re: Setting SharePoint Form Fields Using JavaScript

Left by best online poker site at 12/25/2009 4:40 AM
Gravatar
This action will retrieve the 'content' variable from the form POST variables and do something with it. Finally, it will return a simple message back to the client (as expected by the jQuery tutorial I'm using..

Your comment:



 (will not be displayed)


 
 
 
 
 

Live Comment Preview:

 
«March»
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910