Setting SharePoint Form Fields Using JavaScript
Guest Author: Mark Rackley
The SharePoint Hillbilly
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.
Guest Author: Mark Rackley
Mark has been developing software applications for over 15 years filling the roles of Project Manager, Business Analyst, Lead Developer, and Software Architect. He has been involved in projects for such companies as Dell, Motorola, Intel and Agilent Technologies. He has worked in large corporate environments, small software start-ups, and as a consultant. Mark currently works for UNFI where he was introduced to the world of SharePoint and has taken on a lead SharePoint architect role within his organization making key development, administration, and architecture decisions. Mark’s goal is to help ever new architect and developer avoid the frustrations and brick walls he ran into while learning SharePoint.
Blog: http://www.sharepointhillbilly.com
Email: [email protected]
Twitter: http://www.twitter.com/mrackley
- SharePoint Date Filter: Filtering a List by Greater Than or Equal to Date
- Creating a SharePoint List Parent / Child Relationship - Out of the Box
- Passing Multiple Query String Variables Using SPD – Follow Up on Creating Parent / Child List Relationships
- Setting SharePoint Form Fields Using JavaScript
- Tips When Asking For SharePoint Help
- Setting SharePoint Form Fields Using Query String Variables Without Using JavaScript
- Creating a SharePoint List Parent/Child Relationship – VIDEO REMIX
- SharePoint: Populating Drop Down List Field with Data from Different Site
- Building The Right SharePoint Team For Your Organization
Mark,
This article was very helpful and I’ve pasted it into one note. I think it will come in handy on a form I am building this week.
Thanks for the help. I’ll let you know how it goes.
Marcy
Like?
0
0
Hey Mark,
Great article Mark, thanks!
One question – how can you do this for a Person or Group field?
Thanks
Steve
Like?
0
0
Hi Mark,
Nice article! But there is a cleaner and easier way to set field values client side which works across all major browsers! It is a jPoint’s val() function:
set form value ‘Title’:
jP.Form.readForm().Title.val(”your value”);
get form value:
alert(jP.Form.Title.val());
Steve – yes it works with people picker field as well!
For more examples visit: http://www.sharejpoint.com
Like?
0
0
Hi Mark,
Nice article!
But there is a cleaner and easier way to set field values client side which works across all major browsers! It is a jPoint’s val() function:
set form value ‘Title’:
jP.Form.readForm().Title.val(”your value”);
get form value:
alert(jP.Form.Title.val());
Steve – yes it works with people picker field as well!
For more examples visit: http://www.sharejpoint.com
Like?
0
0
Hi Mark,
Good article. I have a problem with a person control on an edit from. I get the values OK using javascript. What I want to is check if a Person field has been set to blank and give an alert. What’s happening is that even though the Person field is cleared when I check using javascript it still has the previous value. It’s only really cleared when the form is submitted. This only happens with the Person fields. Any other control the logic is OK.
Have you seen this? Question is how can I check if a person field is blank on a form like EditForm.aspx?
Thanks
Like?
0
0
For those of you having issues with specific types of form fields, check out the original code produced by MSDN blogs: http://blogs.msdn.com/sharepointdesigner/archive/2007/06/13/using-javascript-to-manipulate-a-list-form-field.aspx
and the discussion that follows. Lots of good ideas that helped move that code forward.
Like?
0
0
Here is a two line “Easy Button” solution:
http://www.sharejpoint.com/examples/
Take a look under “PopulateFromQuerystring” example.
This is cross browser solution which also works with setting ever lovely People Picker.
Like?
0
0
I agree, there have been a lot of good ideas to help us progress with reading and manipulating SharePoint form fields. There has been many improvements over the years starting with reading the <!– comments nodes to identifying fields with the tagname. With the spreading adoption of SharePoint, there are more and more business cases for customization and an increasing number of "technology challenged" individuals trying to make those customizations. So, I think it is about time for another elegant solution, another abstraction.
End user "customizers" / casual devs should not have to know or deal with:
#1 – finding internal field names
#2 – looking up tagname for a certain column type.
#3 – and it could be argued…code itself.
We need to make it easier like Form["Assigned To"].val() for getter and .val("New Value") for setter. Yes. That easy. Or, you can reference with internal name like Form.Assigned_x0020_To.val().
But point #3 is really why we started jPoint. It is a "platform" or library or API, whatever you want to call it, that allows savvy SharePoint developers to be helpful by creating component solutions (we call them jParts, other people call them CEWP scripts or plugins). These jParts are plug and play. We are trying to improve the intelligence of the configuration API so that end users can modify the jPart just like Corasworks web parts, in a tab-oriented or wizard like fashion.
If you agree, checkout http://jPoint.codeplex.com and start using jPoint.Form["Field Name"].val("New Value") to enhance your end user's experience. If you have time, package your solution as a jPart and share with the community. Though, I admit, we have work to do to explain this process a little bit better, but we are working on it. All help is appreciated!
Like?
0
0
I have a choice with multi seiect box assinged. I am using the following code to get the value of the select box “getTagFromIdentifierAndTitle(”select”,”Lookup”,fieldName);” and getTagFromIdentifierAndTitle(”INPUT”,”",fieldName); is returning Null. Please help me thanks.
Like?
0
0