Microsoft SharePoint Designer Team Blog

Using Javascript to Manipulate a List Form Field

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>

Published Wednesday, June 13, 2007 7:23 PM by spdblog

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Boris Gomiunik said:

Great post! Exactly what I need in a lot of my activities.

June 13, 2007 4:52 PM
 

CustomSoft.Blog said:

Die Leute aus dem SharePoint-Designer-Blog haben einen Artikel veröffentlicht, wie Formularfelder mit Hilfe von Javascript manipuliert werden können. Nützlich kann dies bswp. bei Vorauswahlen von Lookup-Fields sein ... Original Artikel (Verfasst

June 14, 2007 2:11 AM
 

SharePoint, SharePoint and stuff said:

Das SharePoint Designer Team beschreibt in einem Artikel , wei man mit Hilfe von JavaScript die Inhalte

June 14, 2007 9:12 AM
 

Dion said:

Thanks for this. It's great to see how you guys are doing it. We have been doing something similar since the Team Services days but I still gleaned a few good ideas from your code (especially in the genericizing aspects). One thing I have been stuck on is how to set one of the new People fields to the Current User by default. Would love to hear if you guys are doing this or have any ideas.

Cheers!

June 14, 2007 7:07 PM
 

Sean said:

This works great!  Now I need help with pre-loading a Business Data lookup field.  It is a combination of a textarea and some other hidden inputs.  HELP!!!!! please :)

June 17, 2007 2:56 AM
 

Suhaib said:

I'm trying to to do something similar were on the same form one field's data is dependant on another field and both these field are lookup fields,  it will be great If you can tell me the names of the application templates using this feature, so that I can take a look how its works.

June 20, 2007 10:56 AM
 

Sharepointer said:

Thanks! I used this code, just modified a bit - to meet my needs... works well!

June 21, 2007 5:49 AM
 

Microsoft SharePoint Products and Technologies Team Blog said:

The following blog entry is a cross-posting from the SharePoint Designer Team Blog . It has received

June 21, 2007 6:08 AM
 

rsriram22 said:

Aha ... A post on what I was looking for.

June 21, 2007 3:17 PM
 

Chad said:

Yes but how do you get this script onto a wiki creation page?

June 26, 2007 10:08 AM
 

Blog del CIIN said:

Siguiendo con la recopilación de recursos iniciada en un post previo , en la nueva entrega de recursos

June 28, 2007 5:45 AM
 

René Hézser said:

One small sugestion. If you test for "theInput != null" you will not get an exception, if the sscript did not find a control:

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);

   if (theInput == null)

   {

     return;

   }

   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);

 }

}

René

June 29, 2007 5:14 AM
 

David said:

Is it possible to get this (or something similar) to work on a Sharepoint 2003 site? It'd be hugely useful for a few projects I'm working on and I can't get the server updated just yet.

July 12, 2007 2:36 PM
 

Christopher Bermingham said:

This is great-

 A coworker of mine came up with a similar method to locate the input field's ID in V2 and now in V3-

I have posted much of it here:

http://bermingham.blogspot.com/2007/07/finding-sharepoint-fields-using.html

July 12, 2007 3:34 PM
 

Marc (the netherlands) said:

Hi Rob,

You're script is working like a charm on the lookup fields. I even found the application template where you used it and found out you used a content editor web part on the newform.aspx so you can edit the javascript directly from sharepoint. Beautiful. I'm not very good with java script and i'm trying to set the default values for two text fields (Single line of text). I've been struggling with your example for one week straight, where it probably takes you 1 minute.

Can you maybe give an example where two fields (Single line of text) are filled by default. Or maybe just explain what i have to specify in your example where you state (// Set HTML element default values here).

I really hope you can help me out.....

Thanks, Marc

July 18, 2007 6:55 PM
 

rsriram22 said:

the following values for a people picker field do not seem to work - something am missing perhaps - did anyone encounter this?

tagName = "textarea"

identifier="TextField"

title="People Picker"

(the 'Title' property for this textarea seems to be hard coded to 'People Picker' and not the display name)

July 27, 2007 12:12 PM
 

Belchski said:

You could add this function to set the value of a text field:

function setTextFromFieldName(fieldName, value) {

 if (value == undefined) return;

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

theInput.value=value

}

August 16, 2007 1:27 PM
 

Tom Byrnes said:

2 questions

Is there a similar command to _spBodyOnLoadFunctionNames.push for onSubmit that can be fired when a user checks a page back in? I need to do some date checking (date C cannot be before date B which cannot be before date A etc...)

Also, I how can I check for and prevent duplicate titles from being added (with document version control on)?

I have tried using the ItemUpdating event (see code below).  When I get a hit the condition arises

I get a message of

                       properties.ErrorMessage = "Title already exists in category: " & duplicateCategoryName

                       properties.Cancel = True

and set the cancel property -

Control passes back to the screen and prompts the user to Exit without Saving, but the values already saved.  

The user can click Exit w/o saving and we are still getting duplicates in the Title field.

This looks to be a bug, but I am not sure... we also need check the title at ItemAdding and that hasn't worked either.

--------------------------------

CODE SAMPLE

--------------------------------

 Public Overloads Overrides Sub ItemUpdating(ByVal properties As SPItemEventProperties)

       Try

           Dim webCollection As SPWebCollection

           Dim strSiteURL As String = properties.WebUrl

           Dim siteCollection As New SPSite(strSiteURL)

           siteCollection.AllowUnsafeUpdates = True

           Dim site As SPWeb = siteCollection.OpenWeb()

           site.AllowUnsafeUpdates = True

           webCollection = site.Webs

           Dim pageTitle As String = ""

           Dim pageItem As SPListItem = properties.ListItem

           Dim pageSynopsis As String = ""

           If pageItem.Level = SPFileLevel.Draft Then

               If Not pageItem("Title") Is Nothing Then

                   pageTitle = pageItem("Title")

                   Dim topLevelSite As SPWeb = site

                   Do While Not topLevelSite.ParentWeb Is Nothing

                       topLevelSite = topLevelSite.ParentWeb

                   Loop

                   Dim currentPage As Guid = New Guid(pageItem("GUID").ToString())

                   If isTitleDuplicate(topLevelSite, pageTitle, currentPage) Then

                       properties.ErrorMessage = "Title already exists in category: " & duplicateCategoryName

                       properties.Cancel = True

                   End If

               End If

               If pageItem.ContentType.Name = "New NCCI Articles" Then

                   If Not pageItem("ArticleSynopsis") Is Nothing Then

                       pageSynopsis = pageItem("ArticleSynopsis")

                       If pageSynopsis.Equals("") Then

                           properties.ErrorMessage = "Synopsis is a required field"

                           properties.Cancel = True

                       End If

                   Else

                       properties.ErrorMessage = "Synopsis is a required field"

                       properties.Cancel = True

                   End If

               End If

           End If

       Catch ex As Exception

           properties.ErrorMessage = "Error in ItemUpdating: " & ex.ToString()

           properties.Cancel = True

       End Try

   End Sub

August 22, 2007 4:18 PM
 

Jason said:

It works well, is there somewhere to find a complete list of Sharepoint Columns & Identifiers?  I'm specifically looking for multiple selection, not a dropdown list select.

thanks,

jt

August 23, 2007 2:35 PM
 

Patrik said:

Can someone indicate on which page in which application template this is used? As such I can look at a real life example.

August 27, 2007 7:12 AM
 

Jeff K said:

An example of the Application Template is the Job Requisitions Server Admin Template.  In the list Candidates, the DispForm.aspx uses Data Views to show items from the Interview Calendar related to the display item.  There is then the link to add a new Interview by passing the user to NewForm.aspx in the Interview Calendar list.  This is where the javasript above lives.

~Jeff K

August 27, 2007 4:29 PM
 

Matt said:

Will this script work when using the Office SharePoint Designer to create a workflow?  I get an error message when I try and add any script to the page.

September 5, 2007 12:13 PM
 

Patrik said:

Hi,

Great post: I managed to elaborate something similar on other pages.

One question.

On the example template, you can schedule an interview on the candidates dispform.aspx page. This gives the CandidateId as querystring parameter to the next target screen where it is used as input to determine the value of a dropdown box.

In my environment I have set up something similar, but I want to give an additional parameter to the following target page, which is used as input for a second dropdown box. My problem is that the second parameter is a lookup field to a list. I managed to pass the value through the target page, but in fact it shouldn't give the value which is displayed on the screen, but the ID of the value in the lookup list. How can I get the ID of that lookup field and pass it through?

Additionally: will the script mentioned here be able to handle two parameters at the same time to determine the dropdown values in the second target page?

September 6, 2007 3:31 AM
 

Phani said:

Can you please give the tag name and identifier for Person/Group field? I need to hide a UserField for my NewForm.aspx. I tried using the multiple Lookup for SharePoint Field Type, but it doesn't work. I also tried few other combinations but no use. Please help.

September 25, 2007 1:02 PM
 

Windows Server said:

There are many choices to customize lists in SharePoint 2007, but one of the more useful techniques is

September 26, 2007 3:58 PM
 

Microsoft Office SharePoint Server said:

There are many choices to customize lists in SharePoint 2007, but one of the more useful techniques is

September 26, 2007 4:10 PM
 

nevillew said:

Hi, I've seem many examples of having a query string item populate a field and java script is a popular answer. It boils down to getting the java script into the aspx page.

My problem is, the newform.aspx page has no where to put the java script. There is no html in it..

This article says there is a _spBodyOnLoadFunctionNames  function but I can not find that....

Basically, I create a custom list... I then use sharepoint designer to go to the newform.aspx file for that list.

The code in the page begins with:

<%@ Page language="C#" MasterPageFile="~masterurl/default.master"

........

........

I was able to get around this by detaching the page from the masterpage. That seems to show the html code, but I don't want to do that, and this article doesn't allude to that...

Can someone help me out on this? Basically, I have no idea where to stick the java script and get it to run base on my situation... I'm confused that I can't find others with this issue...

Help, please..

September 30, 2007 11:21 PM
 

Tobias said:

Hi nevillew,

Jeff said:

An example of the Application Template is the Job Requisitions Server Admin Template.  In the list Candidates, the DispForm.aspx uses Data Views to show items from the Interview Calendar related to the display item.  There is then the link to add a new Interview by passing the user to NewForm.aspx in the Interview Calendar list.  This is where the javasript above lives.

Look at this page and you'll see they use a Content Editor Web Part. Insert this web part and you can insert code onto the page.

October 1, 2007 7:59 PM
 

nevillew said:

Hi, thanks for your response. Sorry, I'm still a bit confused...I do appreciate your help very much....

I'll go through my steps and then list some problems..

1) I create a custom list called test.

2) I create columns Column1, Column2 and Column3.

3) I then go into SharePoint designer and browse to the list. In the list I see the following aspx pages.

   AllItems.aspx, DispForm.aspx, EditForm.aspx and NewForm.aspx.

4) Now, what I want is to be able to do isretrieve data from the url and store it in a field, when the user

   loads NewForm.aspx

The 2 things I notice (while using SharePoint Designer is)

   a) In display view, the controls are not visible. It shows a standard display.

       Refer to http://blog.henryong.com/2007/09/05/how-to-edit-the-form-fields-of-a-sharepoint-list/

   b) When I look at code view, I see aspx code. I don't believe I can stick my java script in here,              

       although from some other sites I read, they imply I can.

Now, this article makes reference to my situation saying that the newform.aspx page is the content page and there is a master page which is used in conjunction with the content page...

The article mentions a function: _spBodyOnLoadFunctionNames but I can't find out where to locate this...

You would think I could google it and get a hundred hits but there is not much on this....

I also need a solution that is modular. I.e only effects this list.

So basically, that is my situation... I'm not sure why thisn isn't confusing others here....

I was able to achieve something by creating a new aspx page and then importing sharepoint content into it.

This created a page that was detached from a master page. It contained <Head> ... etc....

The problem with this method is, it is too much overhead to support these new pages...

I also tried to back them up and restore them but I think because of unique identifiers in the page

it caused issues...

Basically, I've found that trying to get a query string variable into a field causes to much damn pain that its just better to have the user imput the value, although this drives me crazy. You'd think there would be a more simpler out the box way to do this (and please correct me if I am wrong).

So, based on the above can you help me out... Maybe I'm just going off in the wrong direction, but something tells me there is more to this than what this blog states.....

PS, why is the interace for entering comments into this blog so crappy? I'm not complaing, but come on...

October 2, 2007 12:46 PM
 

TracyW said:

Neville

You're not too far off. To execute the code on the newitem.aspx page of this one list, just insert a script tag (pretty much anywhere near the bottom), I generally put them near another script tag and then insert the call to _spBodyOnLoadFunctionNames and then the functions your want called

Insert this code

<script>

_spBodyOnLoadFunctionNames ("Bob");

function Bob() {alert('Hello World'};

</script>

When the page loads you get the alert box.

Hope this helps

October 4, 2007 8:35 PM
 

Tom Resing said:

I agree with the previous posters. _spBodyOnLoadFunctionNames is undocumented. Should we settle for the fact that the SharePoint Designer Team bothered to mention it briefly in this blog post. Where is it in the SDK docs or MSDN? Is there a corresponding OnUnload function? Proper use of Google Maps requires unloading what you load and I can only guess without proper documentation.

October 11, 2007 10:46 AM
 

Denis Kitchen said:

I noticed a lot of folks want to set the People Picker (Assigned To) field.

Adding this to the fillDefaultValues function worked for me:

var assignedToInput = getTagFromIdentifierAndTitle("div", "", "People Picker");

assignedToInput.innerHTML = vals["Assigned_To"];

Cheers!

October 11, 2007 11:25 AM
 

cnovaksmart said:

I've been trying to use the code listed above and have been having trouble getting it to execute.  I think it might be due to where I've placed the call to _spBodyOnLoadFunctionNames. One of the posts says to add a Content Editor Web Part and then add the call to the page. THis still does not work for me.  Is it possible to get an example showing where exactly this call has been inserted within a sharepoint page, meanign a good chunk of the page?  Thanks!!

October 18, 2007 10:26 AM
 

Tom said:

Are there any other blogs or sites similar to this one which would help me understand how to create CSS/Javascript-based tooltips for each calendar event in the Month/Week/Day calendar views??

Thank you, Tom

November 5, 2007 11:26 AM
 

Jonathan said:

First off, to people having trouble getting it working, simply place the script block within any content area that renders on the page.  Probably the safest bet to make sure it gets on is the main page placeholder.

<script language="javascript" type="text/javascript">

_spBodyOnLoadFunctionNames.push("hideFields");

function hideFields()

{

  //test it first!

   alert('It Worked!!');

}

</script>

Throw the script block from above in directly below <asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server"> and if you get the message box on page load than you've taken care of loading javascript onto the page and can begin working on the next steps.  

Now to my problem...

I've had success with everything except the Recurrence and Workspace fields.  I'm using them as below:

//Recurrence

var control5 = getTagFromIdentifierAndTitle("INPUT","BooleanField","Recurrence");

control5.parentNode.parentNode.parentNode.style.display="none";

I'm getting 'parentNode is null or not an object'.  Any help would be greatly appreciated.

November 5, 2007 7:11 PM
 

Ben said:

Thanks for this post!

Can the same be accomplished with a document library where the properties are shown in for example the properties pane in Word (2007)? I need to accomplish the same for these libraries. Any other suggestions?

Thank you, Ben

November 6, 2007 7:38 AM
 

Geoff G said:

All -- I was able to get regular Text Fields auto-populating from a querystring {NewForm.aspx?myQueryStringName=some_value_here} with this script below. Note i used the function from Belchski {THX!!} called 'setTextFromFieldName' and called it at the bottom of the script like so:   [setTextFromFieldName("theFormFieldDisplayNametoPopulate", vals["myQueryStringName"]);]. I opened NewForm.aspx up in DEsigner & plopped the script right above the </asp:Content> tag.

I hope this works for everyone...GREAT little script. I am using for a link from the Remedy Help Desk App to autopopulate a HD Ticket Number & Summary into a User Survey (how was your Ticket completed, etc.).

----------------------------------------------------------------------

<script type="text/javascript">

_spBodyOnLoadFunctionNames.push("fillDefaultValues");

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;

}

function setTextFromFieldName(fieldName, value) {

if (value == undefined) return;

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

theInput.value=value

}

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

 }  

 setTextFromFieldName("theFormFieldtoPopulate", vals["myQueryStringName"]);

}

</script>

----------------------------------------------------------------------

November 9, 2007 2:14 PM
 

Skullcrusher said:

I was just about to try and write something like this myself for setting the value of a Lookup field but thought I'd do a quick google first.

Thank god I did as this has saved me loads of time and was exactly what I was after.

Thanks for sharing!!

November 18, 2007 4:38 PM
 

GirlGeek said:

my question revolves around the old fashioned document.myform.myfieldname.value='text';

doesn't this work with SharePoint Designer (for the Form Web Part)?

November 26, 2007 3:35 AM
 

jules said:

hi,

what should i use to get the ID of the current item in EditForm.aspx please?

November 29, 2007 1:45 AM
 

Tim Staddon said:

Hi,

Just in case anyone's wanted it, here's a routine to toggle a Yes/No field which is presented via a checkbox:

function setYesNoFromFieldName(fieldName) {

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

  if (theInput.checked=="True") {

  theInput.checked="False";

  } else {

  theInput.checked="True";  

  }

}

November 29, 2007 10:05 AM
 

echef said:

I recently found an application of the Blog template that was a great fit, but needed the Category title

December 27, 2007 2:06 PM
 

SHAREPOINTBlogs.com Mirror said:

I recently found an application of the Blog template that was a great fit, but needed the Category title

December 27, 2007 2:10 PM
 

buggsy2 said:

Anyone have an example of a Web Service call to get default field values?

January 9, 2008 3:49 PM
 

Mirrored Blogs said:

The other title for this blog is &quot;For the Love of Pete, This Should be Easier!&quot; When you make

January 9, 2008 7:52 PM
 

SharePoint 1970 said:

I had a small project in SharePoint 2007 where I needed to pull in Querystring variables from a URL into

January 18, 2008 5:21 PM
 

RamUday said:

The tagName for a multiple lines of text field seems to be "textarea".

When i passed "input" as the tagName for a multi line text box, the multi line field were not being returned.

It works with "textarea".

January 23, 2008 10:10 AM
 

RamUday said:

I have being trying to assign a value to a multi line text box using a javascript function.

the value should get set when the user click on a link in the page.

I could not set the value after the page is rendered.

When I used _spBodyOnLoadFunctionNames.push() to execute the same javascript function on body load, the value is being set correctly.

The same is not happening when the javascript function is called after the page is rendered(i.e. when the user clicks the link)

Does anybody have any lead on this

January 24, 2008 8:29 AM
 

Sharon said:

Same as Jason's question, does anyone know where a complete list of SharePoint Field Type identifiers are?

Thanks.

February 5, 2008 12:13 AM
 

Minou325 said:

Does anyone know the identifier for a HiddenField?

February 5, 2008 4:43 PM
 

Markuso said:

I've also found a way to get a reference to a <strong>Radio Buttons Choice</strong> field type that was tricky to get at since it doesn't use the 'Title' attribute. Please see below:

<a href="http://blog.markuso.com/posts/9/using-javascript-to-access-a-list-form-field-in-sharepoint-designer/">http://blog.markuso.com/posts/9/using-javascript-to-access-a-list-form-field-in-sharepoint-designer/</a>

February 6, 2008 5:34 AM
 

Markuso said:

I've also found a way to get a reference to a Radio Buttons Choice field. It was tricky to get at since it doesn't use the 'Title' attribute. Please see below:

http://blog.markuso.com/posts/9/using-javascript-to-access-a-list-form-field-in-sharepoint-designer/

February 6, 2008 12:07 PM
 

T. said:

Thank you for the great script!  Does anyone know how to get the time portion of a date/time field (DateTimeFieldDate)?

February 7, 2008 4:12 PM
 

Matt said:

Using Script from http://blog.markuso.com/posts/9/using-javascript-to-access-a-list-form-field-in-sharepoint-designer/

how can i use?

Original Poste (October 11, 2007 10:46 AM Denis Kitchen)

var assignedToInput = getTagFromIdentifierAndTitle("div", "", "People Picker");

assignedToInput.innerHTML = vals["Assigned_To"];

So far I have this..... but it does not work and does not reference the particular one I need.... I am just trying to hide it.

   var tagName = "div"

   var identifier = ""

   var FieldName = "People Picker"

   var control = getTagFromIdentifierAndTitle(tagName,identifier,FieldName, Option);

   control.style.display=“none”;

------------------------------------------------------------------------------------------------------------------------

Also note another method from CleverWorkarounds that might be usable......by someone who understands it.  I could not.

http://www.cleverworkarounds.com/category/sharepoint/application-development/javascript/

What they have noticed is every contol SharePoint creates marks it with a commented name.  So by searching for the commented name you should be able to locate the control with in that area perdicably per each control... I just lack understand of the code and it use/syntax to figure out why it does not work for me.

function findacontrol(FieldName) {

  var ctrl = null;

  var arr = document.getElementsByTagName(‘!’);//get all comments

for (var i=0;i < arr.length; i++ )

  {

     // now match the field name

      if (arr[i].innerHTML.indexOf(FieldName) > 0) {

         return arr[i];

      }      

  }

}

function hideFields() {

     var control = findacontrol(“Device Name”);

     control.parentNode.parentNode.style.display=“none”;

     control = findacontrol(“Comments”);

     control.parentNode.parentNode.style.display=“none”;}

     control = findacontrol(“Options”);

     control.parentNode.parentNode.style.display=“none”;}

}

February 8, 2008 9:07 AM
 

Raymond Mitchell said:

Wow, what a day.&#160; Some highlights: Kurt DelBene gave another keynote address following Bill Gates

February 12, 2008 2:24 AM
 

singh30oct said:

Hi

can you send me some code

any user create only 1 item in lookup kist box

February 13, 2008 1:18 AM
 

Matt said:

Good post, thanks for this.  It works well.

However, I want to set a default value of a lookup field in a publishing page, only the first time a user creates the page.

First problem, is setting the field value by actual value of the field, not the index.  Currently the comparison and assignemnt is done based on ID.  How can I assign a string value to the field?

Second, this default value is set every time a user renders the page.  I need to find a way where the default value is only set the first time a page is created.

Any help would be appreciated.

February 13, 2008 10:47 AM
 

Marius Mans said:

Great, Great Great. I combined this with a Insert Template and Magic !!!. Thanks very much.

February 14, 2008 12:50 PM
 

sanjaya said:

hi Matt,

From the earlier postings i understand that you had a problem with People field.

Were u able to find the solution???

i am facing the same problem.

I have 3 to 4 user fields in my newform.aspx, how do i find them through javascript and set the default values.

any help frm anybody would be appreciated..

February 15, 2008 2:13 PM
 

Ramadan said:

thanks for the nice article. helped me out... yet i still have a javascript problem with sharepoint:

I have a publishing site with some pages. i wanted to do something basic stuff like toggling a div visibility when someone clicks a link. i managed to include the javascript function in the page (in the ArticleLinks.aspx page... adding it to the master did not do the job) but looks like there is no way to call the javascript function from the page!

each time i edit the page and go into the source code... adding the javascript function call to the URL or the OnClick is always removed... this is so annoying!!!

such a thing should take 5 mintues and untill now it took me 4 hours...

apperciate if you could help out with this,

Ramadan

February 17, 2008 3:22 AM
 

Lyndon said:

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!

February 20, 2008 5:51 PM
 

chuasteve said:

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.

March 4, 2008 9:12 PM
 

dosboy said:

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

March 6, 2008 7:40 AM
 

Troy said:

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

March 15, 2008 1:07 AM
 

Massimo Prota's BLog said:

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

March 18, 2008 2:08 AM
 

jjthomas said:

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

March 18, 2008 5:11 AM
 

frikouflios said:

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

March 18, 2008 11:54 AM
 

jjthomas said:

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')}" />

March 19, 2008 2:55 AM
 

ronald said:

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

March 22, 2008 3:56 PM
 

Blog del CIIN said:

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

March 27, 2008 11:41 AM
 

Soudip said:

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

March 30, 2008 6:27 AM
 

Skullcrusher said:

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

April 9, 2008 4:15 PM
 

mani said:

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

May 1, 2008 2:28 AM
 

sukebeta said:

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;

}

May 14, 2008 2:55 PM
 

Monty said:

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

May 16, 2008 1:58 PM
 

Mirrored Blogs said:

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

May 29, 2008 5:09 PM
 

ashishkanoongo said:

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.

June 11, 2008 1:29 PM
 

dolomite said:

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

July 11, 2008 2:49 PM
 

dolomite said:

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 = getTagFromIdentifierAndTitl