Geeks With Blogs

News





The SharePoint Hillbilly Fewer Big Words... More Pretty Pictures...

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 on Monday, July 6, 2009 10:18 PM | Back to top


Comments on this post: Setting SharePoint Form Fields Using JavaScript

# re: Setting SharePoint Form Fields Using JavaScript
Requesting Gravatar...
Hey Hillbilly! What's the best way to default a Person field to the currently logged in user? Many thanks!
Left by Steve French on Jul 09, 2009 10:12 AM

# Inserting table rows in Editform with Javascirpt
Requesting 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"
Left by JCNET on Dec 08, 2009 4:26 PM

# re: Setting SharePoint Form Fields Using JavaScript
Requesting Gravatar...
thank you
Left by ally on Dec 15, 2009 3:43 AM

# re: Setting SharePoint Form Fields Using JavaScript
Requesting Gravatar...
hi i am trying to retrieve some values in few fields in my list newform.aspx depending on an input value which is also a field in the list. I Have created a button and a webservice to retrieve the values which takes an input parameter and queries the database to return the result in dataset.
now i am stuck in writing the event on the button which will pass one of the list value as an input parameter and populates the 4 fields with the values retireved by the web service.....
Any Help Please on this
Left by uttam on Jul 06, 2010 9:29 PM

# re: Setting SharePoint Form Fields Using JavaScript
Requesting Gravatar...
Hello there Hillbilly,
Where do I insert the jscript code?
I have inserted a "hello world" in several places of my NewForm.aspx and it does show up, however the actual code to obtain and default to currentuser in a picklist does not work.
<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("fillDefaultValues");

function fillDefaultValues()

document.write('Hello World');

{
fillPeoplePickerWithCurrentUser('Project_x0020_Lead');
}

function fillPeoplePickerWithCurrentUser(pickerName)
{
//get the current user from the welcome menu
var currentUser = getCurrentUser();

//check to see that we've got it
if(currentUser != null)
{
//get the people pickers input div
var pp = getPickerInputElement(pickerName);
//set it to the current user if we've found it
if(pp != null)
pp.innerHTML = currentUser;
}
}

function getCurrentUser()
{
var tags = document.getElementsByTagName('a');
for (var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) == 'Welcome')
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
}
}
}

function getPickerInputElement(fieldsInternalName)
{
var result = "";
var divs = document.getElementsByTagName("DIV");
for(var i=0; i < divs.length ; i++)
{
if(divs[i].id=="WebPartWPQ2")
{
var tds = divs[i].getElementsByTagName("TD");
for(var j=0; j < tds.length; j++)
{
var cellHTML = tds[j].innerHTML;
if(cellHTML.indexOf('FieldInternalName="' + fieldsInternalName + '"') >= 0)
{
var innerDivs = tds[j].getElementsByTagName("DIV");
for(var k=0; k < innerDivs .length; k++)
{
if(innerDivs[k].id.indexOf("UserField_upLevelDiv") > 0)
{
result = innerDivs[k];
break;
}
}
}
}
}
}
return result;
}
</script>
Please help.
Left by elzopi on Jul 29, 2010 12:32 PM

# re: Setting SharePoint Form Fields Using JavaScript
Requesting Gravatar...
I don't suppose anyone has a solution for Custom ist Forms that use the SharePoint:FormField element?

The rendering method seems to be a little different and the expected Title value is not applied to the fields at run-time.
Left by Panoone on Sep 28, 2010 8:11 PM

# re: Setting SharePoint Form Fields Using JavaScript
Requesting Gravatar...
Hi,

The code is not working in firefox,,, :(

Could you please provide some solution?

Thanks
Left by Akmal on May 13, 2011 4:19 AM

Your comment:
 (will show your gravatar)


Copyright © Mark Rackley | Powered by: GeeksWithBlogs.net