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

July 11, 2008 4:34 PM
 

WW said:

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.

July 13, 2008 1:50 AM
 

Rajesh said:

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

July 28, 2008 12:18 AM
 

Candace said:

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.

July 29, 2008 2:28 PM
 

Candace said:

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

July 31, 2008 11:45 AM
 

Jose Otavio Ferreira Soares said:

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.

August 4, 2008 2:08 AM
 

Swathi W said:

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

September 12, 2008 7:45 PM
 

Chris said:

Hi,

What is the tagname for a person/group?

Thanks

Chris

sammutchris@hotmail.com

sammutchris@gmail.com

September 26, 2008 9:49 AM
 

Bobby Vastakis said:

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

October 3, 2008 10:49 AM
 

bob e said:

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

October 13, 2008 12:05 PM
 

bob e said:

fty - That line in my core.css is:

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

October 13, 2008 12:13 PM
 

Tibor said:

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?

October 15, 2008 11:31 AM
 

Eduardo Dias said:

Hi, I am trying to get the "Assigend To" filed value, I used the sugestion above but didn´t work, somebody knows how to get this field?

Regards,

Eduardo

October 20, 2008 4:29 PM
 

Dan Holme said:

October 21, 2008 6:00 AM
 

cristina said:

Could someone give an idea how to have two pre-autopopulation  items such as  newform.aspx?report=Recruiter%20Center&age=20  ?

regards,

Cristina

October 29, 2008 2:35 PM
 

Tuesday said:

I'd like to reuse the setLookupFromFieldName or setSelecttedOption in an inline javascript to change the value of the ListForm field bound to a Sharepoint List.

1. Project ID is the field name for the dropdown I'm trying to set.

2. @Timesheet_ID is the value I want to set the dropdown to. It will always be known, and will always be in the dropdown list as an option.

My design is this: The user clicks on the link below (timesheet ID is loaded prior) to fire off the javascript. I want the dropdown in the other web part to go to that timesheet ID. Is this possible or am I continuing to waste time?

A sample timesheet ID value would be "#222 - IT Infrastructure"

<a href="#" onclick="setLookupFromFieldName('Project ID', {@Timesheet_ID})">

  <xsl:value-of select="@Timesheet_ID" />

</a>

Please help - this is driving me nuts!

October 30, 2008 11:10 AM
 

Jean said:

I'm trying to use something semilar  sukebeta  code which does not seem to be working. I have a script at the bottom of the Edit.aspx page, I need to prevent users setting a drop down field to approved if a couple fields are left empty. I can't set these fields to be required as the person that enters the request  does not do approval and those semi required fields doe not pertain to him.

I have this working in a simple html and JScript page but the sharepoint portion makes it complicated.

Any help would be much apprecaite.

November 7, 2008 12:38 PM
 

Javier Regusci said:

WORKARROUND for setting datetime hour and minute fields

Here is a workarround for setting the values for start/end hours and start/end minute in a Task form. Since the ID for those select contros is generated dinamically i've implemented 2 functions which search for the ones that have the string "00:" for hours and "05" for minutes. I know it's not an elegant way to do it but it will have to do until i can find a way to get the ID for those controls. (Hopefully SP will always render the controls in the same order, because otherwise the values will get set in the wrong order).

   function setHours(startHour, endHour) {

 var tags = document.getElementsByTagName("select");

 var value = startHour;

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

       var select  = tags[i];

       if (select != null && select.options!=null && select.options[0] != null){

           if (select.options[0].value.indexOf("00:") >= 0 ) {

                setSelectedOption(select, value);

            value = endHour;

           }

       }

 }

   }

   function setMinutes(startMinute, endMinute) {

 var tags = document.getElementsByTagName("select");

 var value = startMinute;

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

       var select  = tags[i];

       if (select != null && select.options!=null && select.options[0] != null){

           if (select.options[1].value.indexOf("05") >= 0 ) {

               setSelectedOption(select, value);

            value = endMinute;

           }

       }

 }

   }

For example, a call would be:

     setHours("09:", "10:");

     setMinutes("05, "10");

Remember to append the ":" for the hour fields!

Please let me know if anyone found a better way to do it. Thanks.

December 1, 2008 10:52 AM
 

realite said:

really nice work, in my scenario there is a problem with post back and i hope to i can solve with this solution. Thanks a lot

December 3, 2008 9:18 AM
 

Michael Hill said:

Thanks to Rob and to the many commenters for this code. I needed to populate a custom column when uploading documents so I used this tip on EditForm.aspx. My parameter value is in the URL when the upload button is pushed, but by the time I get to EditForm.aspx, the Source URL has been encoded (the "?" to "%3F" and "=" to "%3D"). So I just had to insert a couple of lines to convert those characters. If I had more than one parameter, I guess I would have had to add an additional line to convert "%26" to "&".

 var qs = location.search.substring(1, location.search.length);

 qs = qs.replace("%3F","&");

 qs = qs.replace("%3D","=");

The other thing I added was to check to see if "Mode=Upload" was in the URL so it would only populate the field on upload.

December 9, 2008 5:23 PM
 

Ramesh Krishnan said:

Great Post.

Is it possible to do this for the Document Library (or is it possible to do the meta data and the uploading on the same page?)

Thanks

ramesh

January 19, 2009 2:00 PM
 

sandy said:

I don't have sharepoint designer but this thread looks like where I should post my question.

Below is the .asp code from a non sharepoint webpage:

 <form method="POST" onSubmit="return validateOnSubmit()" action="http://mysite/ByeBye.aspx" name="requestSend">

<table cellpadding="2" cellspacing="2" border="0">

<tr>

<td class="relativeText">Name*:</td>

<td><input type="text" size="20" name="from" onChange="validateformat(this,'v_from');" value="Sandra Chamberlion"></td>

<td width="25%" id="v_from" class="error">&nbsp;</td>

</tr>

<tr>

<td class="relativeText">Phone*:</td>

<td><input type="text" size="10" maxlength="10" name="phone" onChange="validateExt(this, 'v_phone', true);" value="0000000000"></td>

<td id="v_phone" class="error">&nbsp;</td>

</tr>

<tr>

<td class="relativeText">Contact*:</td>

<td><input type="text" size="30" name="email" onChange="validateEmail(this, 'v_email', true);" value="schamberlion@x.com"></td>

<td id="v_email" class="error">&nbsp;</td>

</tr>

<tr>

<td class="relativeText">Weekdays*:</td>

<td valign="top">

<select class="sidetext" name="days" onChange="validatePresent(this, 'v_days);">

<option value="">&nbsp;</option>

<option value="Monday">Monday</option>

<option value="Tuesday">Tuesday</option>

<option value="Wednesday">Wednesday</option>

<option value="Thursday">Thursday</option>

<option value="Friday">Friday</option>

<option value="Saturday">Saturday</option>

<option value="Sunday">Sunday</option>

</select> </td>

<td id="v_days" class="error">&nbsp;</td>

</tr>

<tr>

<td colspan="3" align="right"><input type="reset" value="Cancel">

<input type="Submit" value="Submit Request" name="Send"></td>

</tr>

</table>

</form>

Above is the asp code from a page, say page A,  where people fill out a form like name, phone, email, etc and hit submit button. In my sharepoint site, say page B, I have created a custom list with exactly same fields as it appears in the form. When the user fills the information in page A and hits submit button, how do I pass those values to prepopulate in the custom list when I open page B. both page A and page B are on different servers now? How would it be done if they were in the same server. if it can be done, where exactly I need to do the change in code?

January 21, 2009 3:41 PM
 

tom daly said:

I was unable to get this to work with my list of 27 form fields.

getTagFromIdentifierAndTitle("input","","Title"); returns  tags Count = 0;

getTagFromIdentifierAndTitle("*","","Title"); returns tags count = 9 .. some <TITLE> <SCRIPT> <META>

all my form fields are text boxes, and 1 multiline textbox.

January 21, 2009 11:23 PM
 

SP Designer said:

 Thanks this is working well for me-  I just have an issue.  Some of the fields that I am populating from the URL on the NewForm need to be read-only and some hidden.

 I have tried making the read-only field a Label, but then cannot access the field in javascript.

 I tried making the hidden field property visible=false but it seems as if the field does not exist on the page when rendered and therefore cannot set the value in javascript.

 How can I populate (from query string parms) read-only and hidden fields on the NewForm?

Thanks

February 9, 2009 3:53 PM
 

Rob said:

Hey,

For Rich Text Fields (i.e., Multiple Lines of Text), the tagName is "textarea" and not "input" as shown in the table at the top.

Also, in my case where I am modifying a copy of NewForm.aspx, it seems that BooleanField can not be found.  So, I simply looked up the field id (use Browser - right-click View Source) and created:

function setYesNoFrimFieldId(id, value)

{

  if (( value == undefined) || ( id == undefined) return;

  var b = document.getElementById( id );

  var newBoolean = false ;

  var newOnOffVal = "off";

  if ( value == 1 || value == true || value == "true" )

  {

       newBoolean = true ;

       newOnOffVal = "on";

  }

  b.checked = newBoolean ;

  b.value = newOnOffVal ;

}

Great post.  Keep the dialog going.

February 19, 2009 1:19 AM
 

SharePoint 1970 said:

This is a bit like &quot;Part II&quot; to my original post [ http://www.sharepointblogs.com/ggill1970

March 2, 2009 4:16 PM
 

Parth said:

Please.. Please reply for the following question that i have.

I just would like to know that where would i define "QUERYSTRING VARIABLE NAME " before using them into following

setLookupFromFieldName("<<FIELD DISPLAY NAME _1>>", vals["<<QUERYSTRING VARIABLE NAME _>>"]);

setLookupFromFieldName("<<FIELD DISPLAY NAME_2>>", vals["<<QUERYSTRING VARIABLE NAME_2 >>"]);

Do i have to define them into dataview?? I m currently using this logic to auto populate one drop down. Works gr8, but wne i try and do it for 2 drop down, i get random values selected into second drop-down. Would you please share something that can help little extra.

Thanks

March 12, 2009 1:36 PM
 

alienout said:

Please.. Please reply for the following question that i have.

I just would like to know that where would i define "QUERYSTRING VARIABLE NAME " before using them into following

setLookupFromFieldName("<<FIELD DISPLAY NAME _1>>", vals["<<QUERYSTRING VARIABLE NAME _>>"]);

setLookupFromFieldName("<<FIELD DISPLAY NAME_2>>", vals["<<QUERYSTRING VARIABLE NAME_2 >>"]);

Do i have to define them into dataview?? I m currently using this logic to auto populate one drop down. Works gr8, but wne i try and do it for 2 drop down, i get random values selected for second dropdown. I m using ID - query string to pass the values from previous page. Would you please share something that can help little extra.

Thanks

March 12, 2009 1:41 PM
 

Rennick said:

Can anyone please help me hide a form field of type "Persons and Groups" in newform.aspx using the javascript I used here in the following post. Everything hides except the "Persons and Groups" type of field :-(

http://www.cleverworkarounds.com/2008/02/07/more-sharepoint-branding-customisation-using-javascript-part-1/

Really would appreciate anyone's help. A post here to share would be great. Thanks, Rennick

March 31, 2009 9:51 AM
 

sellwong said:

Hi all,

I want to compare the date and time in the list from sharepoint, i used the following script to compare two dates but i don't know how to compare the times. please advice, thx

function PreSaveAction()

{

var date1 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Start Date");

var date2 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","End Date");

var arrDate1 = date1.value.split("/");

var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);

var arrDate2 = date2.value.split("/");

var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);

if(useDate1 > useDate2 || useDate1 > today || useDate2 > today)

{

alert("The End Date cannot happen earlier than the Start Date");

return false; // Cancel the item save process

}

return true; // OK to proceed with the save item

}

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;

}

April 8, 2009 3:35 AM
 

sellwong said:

Hi,

I used the following javascipt to validate the date filed of my sharepoint list currently.

function PreSaveAction()

{

var date1 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Start Date");

var date2 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","End Date");

var arrDate1 = date1.value.split("/");

var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);

var arrDate2 = date2.value.split("/");

var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);

if(useDate1 > useDate2 || useDate1 > today || useDate2 > today)

{

alert("The End Date cannot happen earlier than the Start Date");

return false; // Cancel the item save process

}

return true; // OK to proceed with the save item

}

But it cannot validate the time field, please kindly help me to resolve this problem.

thx

April 8, 2009 10:14 PM
 

Pradeep said:

Hi ur Blog was exactly what the doctor ordered........

but there is loop  hole in that  code

when we have multi look up column   Lookup (multiple) , There we have to append  Title

with "possible values"  or "selected values"

here si the change required

   function getTagFromIdentifierAndTitle(tagName, identifier, title) {

     var len = identifier.length;

// for first look up  select box

           title = title + " possible values";

// // for 2 nd look up  select box

           title = title + " selected values";

     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;

   }

April 16, 2009 6:55 AM
 

Mark Stokes said:

Person fields are tough.  I am trying to work on this now.

The difficult bit is that a person field contains many controls on the page, as shown below:

<span dir="none">

<input name="ctl00$m$g_1fc260be_de66_4e85_9a87_866e6694f4c8$ff18_1$ctl00$ctl00$HiddenUserFieldValue" type="hidden" id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_HiddenUserFieldValue" />

<span id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField" class="ms-usereditor" nomatchestext="&lt;No Matching Names&gt;" moreitemstext="More Names..." removetext="Remove" value="" allowempty="1" showentitydisplaytextintextbox="0" eeaftercallbackclientscript="">

<input name="ctl00$m$g_1fc260be_de66_4e85_9a87_866e6694f4c8$ff18_1$ctl00$ctl00$UserField$hiddenSpanData" type="hidden" id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_hiddenSpanData" />

<input name="ctl00$m$g_1fc260be_de66_4e85_9a87_866e6694f4c8$ff18_1$ctl00$ctl00$UserField$OriginalEntities" type="hidden" id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_OriginalEntities" value="&lt;Entities /&gt;" />

<input name="ctl00$m$g_1fc260be_de66_4e85_9a87_866e6694f4c8$ff18_1$ctl00$ctl00$UserField$HiddenEntityKey" type="hidden" id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_HiddenEntityKey" />

<input name="ctl00$m$g_1fc260be_de66_4e85_9a87_866e6694f4c8$ff18_1$ctl00$ctl00$UserField$HiddenEntityDisplayText" type="hidden" id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_HiddenEntityDisplayText" />

<table id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_OuterTable" class="ms-usereditor" cellspacing="0" cellpadding="0" border="0" style="border-collapse: collapse;">

<tr valign="bottom">

<td valign="top" style="width: 90%;">

<table cellpadding="0" cellspacing="0" border="0" style="width: 100%; table-layout: fixed;">

<tr>

<td>

<div id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_upLevelDiv" tabindex="0" onfocusin="this._fFocus=1;saveOldEntities('ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_upLevelDiv')" onclick="onClickRw(true, true);" onchange="updateControlValue('ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField')" onfocusout="this._fFocus=0;" onpaste="dopaste();" autopostback="0" class="ms-inputuserfield" ondragstart="canEvt(event);" onkeyup="return onKeyUpRw('ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField');" oncopy="docopy();" onblur="updateControlValue('ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField')" title="People Picker" onkeydown="return onKeyDownRw(this, 'ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField', 3, true, event);" contenteditable="true" style="width: 100%; word-wrap: break-work; overflow-x: hidden; background-color: window; color: windowtext;" name="upLevelDiv">

</div>

<textarea name="ctl00$m$g_1fc260be_de66_4e85_9a87_866e6694f4c8$ff18_1$ctl00$ctl00$UserField$downlevelTextBox" rows="1" cols="20" id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_downlevelTextBox" class="ms-input" onkeydown="return onKeyDownRw(this, 'ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField', 3, true, event);" onkeyup="onKeyUpRw('ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField');" title="People Picker" autopostback="0" style="width: 100%; display: none; position: absolute;"></textarea>

</td>

</tr>

</table>

</td>

<td align="right" valign="top" nowrap="true" style="padding-left: 5px;">

<a id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_checkNames" title="Check Names" onclick="var arg=getUplevel('ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField');var ctx='ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField';EntityEditorSetWaitCursor(ctx);WebForm_DoCallback('ctl00$m$g_1fc260be_de66_4e85_9a87_866e6694f4c8$ff18_1$ctl00$ctl00$UserField',arg,EntityEditorHandleCheckNameResult,ctx,EntityEditorHandleCheckNameError,true);return false;" href="javascript:">

<img title="Check Names" src="http://usoakcwsps502:7001/_layouts/images/checknames.gif" alt="Check Names" style="border-width: 0px;" />

</a>

<a id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_browse" accesskey="B" title="Browse" onclick="__Dialog__ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField(); return false;" href="javascript:">

<img title="Browse" src="http://usoakcwsps502:7001/_layouts/images/addressbook.gif" alt="Browse" style="border-width: 0px;" />

</a>

</td>

</tr>

<tr>

<td colspan="3">

<span id="ctl00_m_g_1fc260be_de66_4e85_9a87_866e6694f4c8_ff18_1_ctl00_ctl00_UserField_errorLabel" class="ms-error"></span>

</td>

</tr>

</table>

</span>

So getting into the right bit is prooving tricky.  I haven't got a solution yet, but am working on it.  I'll post back here if I get anything working.

Mark

April 17, 2009 10:46 AM
 

Socki said:

Hi

Your post are interesting but I have a problem.

I have a sharepoint custom form and javascript don't execute.

Have you any idea to help me?

Excuse me for the english but I am french.

Thanks

Socki

May 11, 2009 11:27 AM
 

Getto said:

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

Why is that - what is the reson for this?

May 14, 2009 5:33 AM
 

Frank_W said:

Hello,

I have tried to add some script code to my SharePoint site (NewForm.aspx and EditForm.aspx ) but it is not working. I simply added the following code near the bottom of the script directly above the </body> tag:

   <script>

_spBodyOnLoadFunctionNames ("Bob");

function Bob()

{

alert('Hello World')

};

   </script>

When opening the two pages nothing happens. Normaly I expected to see a message box.

Does anybody has an idea why the script is not working?

Frank

June 10, 2009 4:09 AM
 

Bill Koontz said:

This is NOT working for me!!! I don't know why, but after pasting the code into my "NewForm.aspx" and testing it in a browser, I notice that regardless of what I put in my querystring I only get the first item from my list in the dropdown.  If I leave the querystring off completely the dropdown is empty, so I'm confident the script is running and attempting to set the dropdown, but for some odd reason, its setting it to the first drop down value no matter what I put in the query string.

Any ideas why that would happen ?!?!?!?

June 12, 2009 10:58 AM
 

Notes For .NET said:

Insert a CustomValidator in a SharePoint Form (New/Edit)

June 14, 2009 9:49 AM
 

Andrea said:

I wonder if there is a method to retrieve the data in the lookup when it has more than 20 items. The "ShowDropdown" function fails, I really don't know why. Can someone help me? It is really important!

June 30, 2009 2:50 AM
 

gitz said:

Great Post!

Anyone can tell me how can i get lookup (mutliple) values depending on which one is clicked ?

Always returns me NULL with  getTagFromIdentifierAndTitle

July 2, 2009 6:31 AM
 

Jeff said:

I've just spent days building out a similar set of functions to prefill form elements, hide "columns", convert other editable fields to read-only, etc. only to discover that when viewing sharepoint pages with Internet Explorer some of the dropdown fields are rendered as some sort of highly modified input field instead of a standard select element (while other dropdown fields use the select element - bizarre!). Where have the select elements gone?!

In an input-element-dropdown field how do you add, remove or sort "options"? How do you determine which "option" is selected? How do you programatically select an "option".

What a nightmare!

July 5, 2009 5:37 PM
 

Andrea said:

Great Rob!

I managed to take control of a single lookup with less than 20 items and of a multiple lookup; still, the simple lookup with more than 20 items fails on "ShowDropdown" function! I really don't understand why... could someone help me? It is really important! I have the ID of the lookup (that is an input, correct); if I query the value of this Lookup it is undefined. I can't access objects inside the lookup when they have more than 20 items.

For Frank W: Try to put the ;(semicolon) after alert('Hello World'); instead of putting it after the bracket!

July 7, 2009 6:21 AM
 

Andrea said:

OK, I'0ve got this snippet nearly working:

Select1ID = "ctl00_m_g_154f7ce6_a92a_47a7_aefd_7f52043cc1a0_ctl00_ctl04_ctl01_ctl00_ctl00_ctl04_ctl00_ctl01";

Lookup1 = document.getElementById(Select1ID);

ShowDropdown(Lookup1.id);

opt1 = document.getElementById(Lookup1.opt);

OptLoseFocus(opt1);

var o = opt1[1]; //or whatever...

opt1.add(o); //this fails!!!!!!!!!!!!!!!!!!!

Does someone knows why the add function fails?

I've discovered this code won't work if you don't use _spBodyOnLoadFunctionNames.push(the function with this code inside).

July 8, 2009 9:31 AM
 

Johnny said:

Referring to the original post, please can someone explain to me like i'm a 10 year old how to get this script to work???

I'm assuming its a CEWP in the newform.aspx. What is the <<FIELD DISPLAY NAME>> supposed to be and what is the <<QUERYSTRING VARIABLE NAME>>? Is one a column name and the other an entry in the column?

What does this function do exactly? I don't quite understand this: "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. "

Sorry but I am completely lost and judging by the responses, this is something not to be missed!

July 10, 2009 8:31 AM
 

Mary Kay Scott said:

Javascript is not executing for me as well.  

It's very odd, because all the javascript in the master page executes just fine -- it's only javascript that is added to individual pages.

I've tried this script (and a "hello" alert) in both the PlaceHolderMain and the PlaceHolderAdditionalPageHead, with no difference.

Has anyone who has experienced this problem found a way to get it to work?  If so, please reply.....

July 29, 2009 9:57 AM
 

Rahul said:

Hi Rob,

I am working on a sharepoint intranet portal, Initially on the master page of the portal it was the simple search option but i want advance search so i changed the search option from simple to advance but litrally i am facing one error when i open my site it shows an error that is error on the page & when i click on the error the description is  "document.getElementByID(...) is null or not an object" on the left bottom side of my page.

My advance search code is belllow:

<DIV id="SearchArea"><TABLE cellSpacing="0" cellPadding="0" width="100%" border="0" TOPLEVEL=""><TBODY><TR><TD vAlign="top"><DIV id="WebPartWPQ1" allowDelete="false" width="100%" HasPers="true" WebPartID="00000000-0000-0000-0000-000000000000" OnlyForMePart="true"><DIV id="SRSB"><DIV><INPUT id="ctl00_PlaceHolderSearchArea_ctl01_ctl00" type="hidden" name="ctl00$PlaceHolderSearchArea$ctl01$ctl00" value="http://devsrv:5555/SME" /><TABLE class="ms-sbtable ms-sbtable-ex" border="0"><TBODY><TR class="ms-sbrow"><TD class="ms-sbscopes ms-sbcell"><SELECT class="ms-sbscopes" id="ctl00_PlaceHolderSearchArea_ctl01_SBScopesDDL" title="Search Scope" name="ctl00$PlaceHolderSearchArea$ctl01$SBScopesDDL"> <OPTION value="This Site">This Site: SME</OPTION> <OPTION value="">All Sites</OPTION> <OPTION value="/searchcenter/Pages/peopleresults.aspx">People</OPTION></SELECT></TD><TD class="ms-sbcell"><INPUT class="ms-sbplain" onkeypress="javascript:return S6AE27B38_OSBEK(event);" id="ctl00_PlaceHolderSearchArea_ctl01_S6AE27B38_InputKeywords" title="Enter search words" style="WIDTH: 170px" accessKey="S" alt="Enter search words" maxLength="200" name="InputKeywords" value="" /></TD><TD class="ms-sbgo ms-sbcell"><A id="ctl00_PlaceHolderSearchArea_ctl01_S6AE27B38_go" title="Go Search" href="javascript:S6AE27B38_Submit()"><IMG onmouseover="this.src='/_layouts/images/gosearch.gif'" title="Go Search" style="BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px" onmouseout="this.src='/_layouts/images/gosearch.gif'" alt="Go Search" src="http://onicra-pcs1:1985/_layouts/images/gosearch.gif" /></A></TD><TD class="ms-sbcell ms-sblink"><A id="ctl00_PlaceHolderSearchArea_ctl01_S6AE27B38_AdvSearchLink" title="Advanced Search" href="/searchcenter/Pages/Advanced.aspx">Advanced Search</A></TD><TD class="ms-sbLastcell"></TD></TR></TBODY></TABLE></DIV></DIV></DIV></TD></TR></TBODY></TABLE></DIV>

Please help me to sort out this problem.

Thanks

Rahul

July 30, 2009 1:22 AM
 

Sam said:

Hi all,

I am trying to 'grab' the values from a newform.aspx (customized) using Javascript in order to calculate a total for an expense form.  I have an expense field, a miles field, a mileage rate field (prepopulated with the default federal standard .550 and ControlMode = "display" so the user cannot accidentally edit the rate.  I have "hidden" this field by enclosing it with a span tag and setting the color to "white" via style.  All fields are given default values.  The idea I am going for is that onload, the script executes, gets the values from the appropriate fields, calculates total = mileagerate*miles + expense and prints the total amount at the bottom of the table.  Additionally, I would like to set the "miles" and "expense" fields to trigger the same function onchange.

My problem is that I am grabbing something, but what i am storing in my variables is not the text or value that the control contains but (I assume) the object ID.  I think this because when I test by printing to screen via document.write([a variable]) I end up with a td cell containing [object].  I am very new to Javascript, everythin I've figured out is from the past two days, some experience with programming.  My script is below, all of which is located immediately the placeholdermain ID.

<script type="text/javascript" src="../../_JS/SPAPI_Core.js" > </script>

<script type="text/javascript" src="../../_JS/SPAPI_Lists.js" > </script>

<script src="../../_JS/jquery.min.js"></script>

<script src="../../_JS/jquery-ui.min.js"></script>

<script type="text/javascript">

_spBodyOnLoadFunctionNames.push("TotalMyStuff");

function TotalMyStuff(){

getField('text','ExpenseAmount').onchange = function() {totalAmount()};

getField('input','Miles').onchange = function() {totalAmount()};

}

function getField(fieldType,fieldTitle)

{

   var docTags = document.getElementsByTagName(fieldType);

   for (var i=0; i < docTags.elements. length; i++) {

       if (docTags[i].title == fieldTitle) {

           return docTags[i]

       }

   }

}

function totalAmount()

{

var expense = getField('text','ExpenseAmount');

var miles = getField('input','Miles');

var mileage = document.getElementById('MileageRate');

totalAmount = miles*mileage + expense;

document.write(totalAmount);

}

getField('text','ExpenseAmount').onchange = function() {totalAmount()};

getField('text','Miles').onchange = function() {totalAmount()};

</script>

Your help is greatly appreciated.

Thanks,

Sam

August 11, 2009 12:27 AM
 

Sam said:

I figured it out.  script is below in case it helps anyone (for internal server T&E tracking)

<script type="text/javascript" src="../../_JS/SPAPI_Core.js" > </script>

<script type="text/javascript" src="../../_JS/SPAPI_Lists.js" > </script>

<script src="../../_JS/jquery.min.js"></script>

<script src="../../_JS/jquery-ui.min.js"></script>

<script type="text/javascript">

_spBodyOnLoadFunctionNames.push("TotalMyStuff");

function TotalMyStuff() {

getField('input','ExpenseAmount').onchange = function() {totalAmount()};

getField('input','Miles').onchange = function() {totalAmount()};

}

function getField(fieldType,fieldTitle) {

   var docTags = document.getElementsByTagName(fieldType);

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

       if (docTags[i].title == fieldTitle) {

           return docTags[i]

       }

   }

}

function toNumber(notNumber)

{

var newNumber = "";

if (isNaN(notNumber))

{

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

{

if (isNaN(Number(notNumber.charAt(i))) && notNumber.charAt(i) != ".")

{

newNumber =  newNumber + "";

}

else

{

newNumber = newNumber + notNumber.charAt(i);

}

}

}

newNumber = Number(newNumber);

return newNumber;

}

function totalAmount() {

var expense = getField('input','ExpenseAmount').value;

var miles = getField('input','Miles').value;

var mileage = document.getElementById('MileageRate').innerHTML;

expense = Number(expense);

miles = Number(miles);

mileage = toNumber(mileage);

calcAmount = expense + (miles*mileage);

document.getElementById('totalexp').innerHTML = calcAmount.toPrecision(4);

}

getField('input','ExpenseAmount').onchange = function() {totalAmount()};

getField('input','Miles').onchange = function() {totalAmount()};

</script>

August 12, 2009 6:13 PM
 

Adam said:

I've spent a while now trying to get this to work now, and have found that setSelectedOption() is not working cause it's trying to match a title string which appears in the lookup field to the corresponding item ID...

Is there something that can be simply changed in the script rather than having to change all the calling pages?

August 17, 2009 2:19 PM
 

Adam said:

In case anyone had the same issue as me, whereby the passed value is the lookup value rather than it's ID, just change the test inside setSelectedOption()'s loop from opts[i].value to opts[i].text, so it should look like blow afterwards.

if (opts[i].text == value)

The rest of your solution works like a charm OP.

August 17, 2009 2:51 PM
 

Jason G said:

Great post, i did have a tricky issue in the setSelectedOption function. I had to change:

if (opts[i].value== value) {

to

if (opts[i].text == value) {

The values stored in my lookup field were just integers, but i was passing the display name in the query string. Once i changed it to match on text it worked great. Thx!

August 28, 2009 9:31 AM
 

Martin Hipfinger said:

hi,

i've a problem with special characters, for instance german oder polish ones - they are not pasted correctly into the fields. how can i solve this? any help would be nice, thx!

martin

September 15, 2009 10:41 AM
 

Mark N said:

Same issue as Frank W and Mary Kay Scott:  javascript doesn't execute regardless of where it is placed on content page (NewForm.aspx for me).  Anyone have an idea?

September 21, 2009 3:16 PM
 

Tom said:

Has anyone run into the situation where when re-populating a choice field drop down, this generates an error when the user hits ok to save the data?  I believe it is because my choice drop down starts with only one option in it (<<Select>>).  I then populate it with several pieces of data using:

function SetOptions(select, value)

{

   var opts = select.options;

   opts.length=value.length+1;

   var l = opts.length;

  if (select == null) return;

  for (var i=1; i < l; i++)

  {

     opts[i].innerText=value[i-1];

  }

  return false;

}

select is the drop down and value is the array of values to populate the control with.  If I select the first option in the array, my form will save using the <<Select>> value.  Any ideas on how to get it to accept my new array of values?

October 12, 2009 6:27 PM
 

Mauricio said:

Hello,

i'm having a problem to hide a control on DisplayForm, couse it becomes a <a></a> tag.

How can i find the control on displayform?

thanks...

October 15, 2009 7:02 AM
 

James said:

Hello -

I simply just want to be able to set the values of fields in my list upon page load.  How would I do that?

I tried to use the example Belchski posted:

function setTextFromFieldName(fieldName, value) {

if (value == undefined) return;

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

theInput.value=value

}

but i'm not quite sure how this works.

So for example

I have one field in my list, which is Title, which is a textfield.

On pageload,  how can I populate the title with a value?

Any help on this would be of much help.

Thank you

October 20, 2009 3:06 AM
 

vj said:

Hi all

I am supposed to populate a sharepoint form created by ANOTHER team (so I have no developer/admin access to make any code changes)

When I populate this form, it has many fields which have fixed values

I am looking for a way to automate filling these fields, and leaving just the other fields unpopulated. As you can see, I cannot use any code/designer method that involves THAT team having to make code changes (although that woldbe the cleanest and most efficient method - but that's corp culture for you)

Maybe a VBA script/macro..is there a way?

FYI - its a custom list form, and has text boxes, lists and radio buttons

Regards

VJ

October 26, 2009 9:46 AM
 

willhlaw said:

VJ and all,

If you are able to add a content editor webpart or script to the page, than you can use the solution that one of the jPoint developers has created.  It is called PopulateFromQueryString and an example is here,   http://www.sharejpoint.com/examples/Lists/PopulateFromQuerystring/NewForm.aspx?Title=hello%20world&Choice=Choice 2&Number=123&Person=demouser&YesNo=0.  It has been tested in IE 6+, FF 3+, and Chrome, as well as on custom pages with the list form web part.

Here is the code that you can cut and paste onto your own site, but it is recommended to download the jPoint.zip file at http://jPoint.codeplex.com and put the files into a document library.  For the field names in the URL parameter, remove whitespace and special characters.  Just the field names; the values can have spaces and such. (i.e. ?AssignedTo=The Team!)

<script type="text/javascript" src="//sharejpoint.googlecode.com/files/jPointLoader-0.6-expanded.js" ></script>

<script>

$(document).ready(function() {

jP.Form.readForm();

$.each(jP.Form.Items, function (idx, item) {

if(querySt(item.Name) != null && querySt(item.Name) != "undefined")

jP.Form[item.Name].val(unescape(querySt(item.Name)));

});

});

//Gets value of querystring key

function querySt(ji)

{

      hu = window.location.search.substring(1);

      gy = hu.split("&");

      for (i=0;i<gy.length;i++)

      {

              ft = gy[i].split("=");

              if (ft[0].toUpperCase() == ji.toUpperCase()) //Fixed query so it is case insensitive

              {

                      return ft[1];

              }

      }

}

</script>

November 3, 2009 7:27 PM
 

ashiena said:

Hye everyone,

in my NewForm.aspx I have two field 'Title' and 'Application List'

Display name is what we can see in the form? Is yes than its : 'Application List'

And my querysting : /%2FPinjaman%2FAllItems%2Easpx%3FFilterField1%3DApplication%255Fx0020%255FList%26FilterValue1%3Dtest

which I would like to set my dropdownlist default value to my filtervalue1 = test

and I set in CEWP in javascript and chnage the following:

1. setLookupFromFieldName("Application List", vals["FilterValue1"]);

2. from someone comment, I change the comparison to (opts[i].innerText== value)

But the default value could not work. How is the correct way?

Hope to get feedback soon...

thank you in advanced...

November 25, 2009 3:22 PM
 

Philipp said:

Hi,

I know it's an old thread, but I spent the last two hours, ok 30 minutes, with the search for the cause that the correct value is not choosen... The solution:

in function setSelectedOption(select, value) the correct command would be if(opts[i].text == value) instead of if (opts[i].value == value)...

November 27, 2009 7:57 PM
 

Shahab said:

Hi geeks,

I`m new in sharePoint and just wondered how could i set the default value for one of my "date/time" fields (say "Issue Start Time")  in newform.aspx with current Time and date.

SP would handle the date portion , but i have painful problems with time portion.  I really appreciate your guide

December 5, 2009 2:51 AM
 

samuel said:

Hi,

I need to access person or Group control on a Sharepoint  List form using javascript. I need tagname and identifier for person or group.. Please Let me know if anyone has an idea.

Thanks,

Samuel Mendu

December 17, 2009 11:20 AM
 

Sri said:

can any one plz provide code for accessing Person or Group control tru Javascript for validation purpose

thanks

srikanth...

January 6, 2010 9:08 AM
 

PrashanthSpark said:

I want to validate when i click on ok button for submit data!

can i use PreSaveItem() function ?

Please let me know.

January 13, 2010 8:15 PM
 

vaishnavi desai said:

Very nice post!!

I am trying to do something similar for lookup column.

I want to be able to fire an onchange() event on lookup field when when value is entered by user in textbox.

So there is a textbox and lookupfield.

When lookupfield has more than 20 items it stops to work in IE.

By using onchange event i want to check(validate) if value entered in textbox already exists in lookup and if so popup a message.

Let me know if you have any questions.

Thanks,

January 15, 2010 3:29 PM
 

Andrej Dahllöf said:

If you are looking for a solution with cascading lookups for MOSS 2007 I can recommend the following over all recipe:

Use regular text fields (columns) and change them dynamically at runtime to combo boxes with help of Jquery. Then use  SPlookup (Codeplex, library to easily use MOSS/WSS web service calls like "get list items) to get/filter values. Lookup values are stored in Sharepoint lists instead of lookup fields. The code for this is implemented as Java Script and then linked in to your  master pages with logic to determine what pages the script should be active on (edit form & new form for example). No need to use CEWP to activate code (just messy).

This gives you two important benefits: A) The values (eg corporate taxonomy) can be managed by permissions on lists/sites instead of giving persons access to "site admin functions" needed to alter lookup column values. B) You avoid the hassle with lookup fields (described above). This "architecture"  also lend itself well to be implemented for DIP (Document Information Panel) where you can easily add combo boxes with values from these SharePoint lists and filter them accordingly.

Best regards

Andrej, Solution architect, TactiQa Technology

January 25, 2010 4:52 AM
 

Kiran K said:

Tag, Identifier, Title for People Picker control is:

Tag = Textarea

Identifier = UserField_downlevelTextBox

Title = People Picker

Here is the JavaScript code to hide People Picker control.

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

_spBodyOnLoadFunctionNames.push("hideFields");

function hideFields() {

var control = getTagFromIdentifierAndTitle("Textarea","UserField_downlevelTextBox","People Picker");

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

}

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>

NOTE: The "People Picker" control was embedded 12 levels "deep" from the <tr> tag in my NewForm.aspx, and hence I had to use the code in the hideFields() function with 12 "parent" references. I used the awesome Firebug tool to view this hierarchy and to also find out the elusive tagName, identifier, and title info for the People Picker control. The Firebug tool is a FireFox browser addon, and is incredibly helpful when you need to look at raw HTML and JavaScript code that renders SharePoint pages.

February 2, 2010 7:38 AM
 

Bob said:

I'm interested in that Andrej - but I'm having trouble finding the exact Codeplex project you're referring to - could you please give a link?

Thanks,

Bob

February 2, 2010 5:07 PM
 

Brandon said:

All these codes are great, but how can i get the text from a lookup field in the DispForm.aspx?

I want to hide fields based on what was selected in a Lookup field when the item is being viewed... I have no problem hiding fields, but getting the text is a problem...

Any ideas?

February 26, 2010 10:54 AM
 

Roland said:

For those who may be having issues with Mutiple Lines of Text (this may be an IE 6 issue, dont know), the above mentioned TagName of Input for Multiple Lines of Text does not work.

You have to use textarea instead. If you have a look at the source code of your page you'll notice this is the tag name.

So recap:

SharePoint Field: Multiple Lines of Text

Type identifier: TextField

tagName: textarea

If this is browser agnostic lets update the above table with the correct info.

Hope that helps someone...

March 5, 2010 7:06 AM

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Submit

© 2010 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker