Partilhar via


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

Comments

  • Anonymous
    June 13, 2007
    Great post! Exactly what I need in a lot of my activities.

  • Anonymous
    June 13, 2007
    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

  • Anonymous
    June 14, 2007
    Das SharePoint Designer Team beschreibt in einem Artikel , wei man mit Hilfe von JavaScript die Inhalte

  • Anonymous
    June 14, 2007
    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!

  • Anonymous
    June 16, 2007
    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 :)

  • Anonymous
    June 20, 2007
    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.

  • Anonymous
    June 20, 2007
    Thanks! I used this code, just modified a bit - to meet my needs... works well!

  • Anonymous
    June 20, 2007
    The following blog entry is a cross-posting from the SharePoint Designer Team Blog . It has received

  • Anonymous
    June 21, 2007
    Aha ... A post on what I was looking for.

  • Anonymous
    June 26, 2007
    Yes but how do you get this script onto a wiki creation page?

  • Anonymous
    June 27, 2007
    Siguiendo con la recopilación de recursos iniciada en un post previo , en la nueva entrega de recursos

  • Anonymous
    June 28, 2007
    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é

  • Anonymous
    July 12, 2007
    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.

  • Anonymous
    July 12, 2007
    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

  • Anonymous
    July 18, 2007
    The comment has been removed

  • Anonymous
    July 27, 2007
    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)

  • Anonymous
    August 16, 2007
    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 }

  • Anonymous
    August 22, 2007
    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

  • Anonymous
    August 23, 2007
    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

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

  • Anonymous
    August 27, 2007
    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

  • Anonymous
    September 05, 2007
    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.

  • Anonymous
    September 05, 2007
    The comment has been removed

  • Anonymous
    September 25, 2007
    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.

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

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

  • Anonymous
    September 30, 2007
    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..

  • Anonymous
    October 01, 2007
    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.

  • Anonymous
    October 02, 2007
    The comment has been removed

  • Anonymous
    October 04, 2007
    The comment has been removed

  • Anonymous
    October 11, 2007
    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.

  • Anonymous
    October 11, 2007
    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!

  • Anonymous
    October 18, 2007
    The comment has been removed

  • Anonymous
    November 05, 2007
    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

  • Anonymous
    November 05, 2007
    The comment has been removed

  • Anonymous
    November 05, 2007
    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

  • Anonymous
    November 09, 2007
    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>

  • Anonymous
    November 18, 2007
    The comment has been removed

  • Anonymous
    November 25, 2007
    my question revolves around the old fashioned document.myform.myfieldname.value='text'; doesn't this work with SharePoint Designer (for the Form Web Part)?

  • Anonymous
    November 28, 2007
    hi, what should i use to get the ID of the current item in EditForm.aspx please?

  • Anonymous
    November 29, 2007
    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";     } }

  • Anonymous
    December 27, 2007
    I recently found an application of the Blog template that was a great fit, but needed the Category title

  • Anonymous
    December 27, 2007
    I recently found an application of the Blog template that was a great fit, but needed the Category title

  • Anonymous
    January 09, 2008
    Anyone have an example of a Web Service call to get default field values?

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

  • Anonymous
    January 18, 2008
    I had a small project in SharePoint 2007 where I needed to pull in Querystring variables from a URL into

  • Anonymous
    January 23, 2008
    The comment has been removed

  • Anonymous
    January 24, 2008
    The comment has been removed

  • Anonymous
    February 04, 2008
    Same as Jason's question, does anyone know where a complete list of SharePoint Field Type identifiers are? Thanks.

  • Anonymous
    February 05, 2008
    Does anyone know the identifier for a HiddenField?

  • Anonymous
    February 05, 2008
    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>

  • Anonymous
    February 06, 2008
    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/

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

  • Anonymous
    February 08, 2008
    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”;} }

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

  • Anonymous
    February 12, 2008
    The comment has been removed

  • Anonymous
    February 13, 2008
    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.

  • Anonymous
    February 14, 2008
    Great, Great Great. I combined this with a Insert Template and Magic !!!. Thanks very much.

  • Anonymous
    February 15, 2008
    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..

  • Anonymous
    February 16, 2008
    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

  • Anonymous
    February 20, 2008
    The comment has been removed

  • Anonymous
    March 04, 2008
    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.

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

  • Anonymous
    March 14, 2008
    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

  • Anonymous
    March 17, 2008
    [SPD Workflows] Manipolazione JS e validazione di custom Collect Data forms

  • Anonymous
    March 17, 2008
    How to set the current user in a people picker field on the newform.aspx

  • Anonymous
    March 18, 2008
    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

  • Anonymous
    March 18, 2008
    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')}" />

  • Anonymous
    March 22, 2008
    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

  • Anonymous
    March 27, 2008
    Siguiendo con la serie de post de construcción de aplicaciones de SharePoint utilizando SharePoint Designer

  • Anonymous
    March 29, 2008
    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!!!!!!!!!

  • Anonymous
    April 09, 2008
    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

  • Anonymous
    April 30, 2008
    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

  • Anonymous
    May 14, 2008
    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; }

  • Anonymous
    May 16, 2008
    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

  • Anonymous
    May 29, 2008
    This blog assumes you are familiar with techniques to add javascript to a SharePoint page (specifically

  • Anonymous
    June 11, 2008
    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.

  • Anonymous
    July 11, 2008
    Well I got the text fields and choice field to auto populate. But does anyone know the identifiers for the date fields?

  • Anonymous
    July 11, 2008
    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>

  • Anonymous
    July 12, 2008
    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.

  • Anonymous
    July 27, 2008
    How to update the drop down boxes of datetime filed using javascript? I need to add +5 to the current Hours..

  • Anonymous
    July 29, 2008
    The comment has been removed

  • Anonymous
    July 31, 2008
    Figured it out... it works for libraries just the same.  The upload.aspx passes the query string through.

  • Anonymous
    August 03, 2008
    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.

  • Anonymous
    September 12, 2008
    The comment has been removed

  • Anonymous
    September 26, 2008
    Hi, What is the tagname for a person/group? Thanks Chris sammutchris@hotmail.com sammutchris@gmail.com

  • Anonymous
    October 03, 2008
    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

  • Anonymous
    October 13, 2008
    The comment has been removed

  • Anonymous
    October 13, 2008
    The comment has been removed

  • Anonymous
    October 15, 2008
    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?

  • Anonymous
    October 20, 2008
    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

  • Anonymous
    October 20, 2008
    See http://blogs.msdn.com/sharepointdesigner/archive/2007/06/13/using-javascript-to-manipulate-a-list

  • Anonymous
    October 29, 2008
    Could someone give an idea how to have two pre-autopopulation  items such as  newform.aspx?report=Recruiter%20Center&age=20  ? regards, Cristina

  • Anonymous
    October 30, 2008
    The comment has been removed

  • Anonymous
    November 07, 2008
    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.

  • Anonymous
    December 01, 2008
    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.

  • Anonymous
    December 03, 2008
    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

  • Anonymous
    December 09, 2008
    The comment has been removed

  • Anonymous
    January 19, 2009
    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

  • Anonymous
    January 21, 2009
    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?

  • Anonymous
    January 21, 2009
    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.

  • Anonymous
    February 09, 2009
     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

  • Anonymous
    February 18, 2009
    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.

  • Anonymous
    March 02, 2009
    This is a bit like &quot;Part II&quot; to my original post [ http://www.sharepointblogs.com/ggill1970

  • Anonymous
    March 12, 2009
    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

  • Anonymous
    March 12, 2009
    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

  • Anonymous
    March 31, 2009
    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

  • Anonymous
    April 07, 2009
    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; }

  • Anonymous
    April 08, 2009
    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

  • Anonymous
    April 15, 2009
    The comment has been removed

  • Anonymous
    April 17, 2009
    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

  • Anonymous
    May 11, 2009
    The comment has been removed

  • Anonymous
    May 13, 2009
    *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?

  • Anonymous
    June 09, 2009
    The comment has been removed

  • Anonymous
    June 12, 2009
    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 ?!?!?!?

  • Anonymous
    June 14, 2009
    Insert a CustomValidator in a SharePoint Form (New/Edit)

  • Anonymous
    June 29, 2009
    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!

  • Anonymous
    July 01, 2009
    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

  • Anonymous
    July 05, 2009
    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!

  • Anonymous
    July 06, 2009
    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!

  • Anonymous
    July 08, 2009
    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).

  • Anonymous
    July 10, 2009
    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!

  • Anonymous
    July 29, 2009
    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.....

  • Anonymous
    July 29, 2009
    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

  • Anonymous
    August 10, 2009
    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 = mileageratemiles + 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 = milesmileage + expense; document.write(totalAmount); } getField('text','ExpenseAmount').onchange = function() {totalAmount()}; getField('text','Miles').onchange = function() {totalAmount()}; </script> Your help is greatly appreciated. Thanks, Sam

  • Anonymous
    August 12, 2009
    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>

  • Anonymous
    August 17, 2009
    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?

  • Anonymous
    August 17, 2009
    The comment has been removed

  • Anonymous
    August 28, 2009
    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!

  • Anonymous
    September 15, 2009
    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

  • Anonymous
    September 21, 2009
    The comment has been removed

  • Anonymous
    October 12, 2009
    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?

  • Anonymous
    October 14, 2009
    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...

  • Anonymous
    October 19, 2009
    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

  • Anonymous
    October 26, 2009
    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

  • Anonymous
    November 03, 2009
    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>

  • Anonymous
    November 25, 2009
    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...
  • Anonymous
    November 27, 2009
    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)...

  • Anonymous
    December 04, 2009
    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

  • Anonymous
    December 17, 2009
    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

  • Anonymous
    January 06, 2010
    can any one plz provide code for accessing Person or Group control tru Javascript for validation purpose thanks srikanth...

  • Anonymous
    January 13, 2010
    I want to validate when i click on ok button for submit data! can i use PreSaveItem() function ? Please let me know.

  • Anonymous
    January 15, 2010
    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,

  • Anonymous
    January 24, 2010
    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

  • Anonymous
    February 01, 2010
    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.

  • Anonymous
    February 02, 2010
    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

  • Anonymous
    February 26, 2010
    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?

  • Anonymous
    March 04, 2010
    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...

  • Anonymous
    March 24, 2010
    This may be useful for some. I have created a method uing JQUERY that allows you to set the value of a BDC field based on the name of the field. Not 100% tested so use at your own risk. function setBDCFieldValue(fieldName, value) { headers = $("h3.ms-standardheader > nobr:contains('" + fieldName + "')"); var requiredTag = ' *'; for(i = 0; headers && i < headers.length; i ++) { if (headers.eq(i).text() == fieldName+requiredTag || headers.eq(i).text() == fieldName) { headers.eq(i).parent().parent().parent().find("textarea").text(value); headers.eq(i).parent().parent().parent().find("div").text(value); } } }

  • Anonymous
    April 06, 2010
    Hi Bob Sorry for the delay in my answer. I spent quit a lot of time doing research around this area for one of my customers. All the solutions I found (like 3:e party and such) had some major drawbacks. This was the cleanest solution (in my opinion) although it required some script coding. I especially needed a "no binary install" solution to this project. Here is the link to the Jquery Web Service utility: http://spservices.codeplex.com/. If you want to ask me more questions I can be reached at  talk2andrej@hotmail.com Best regards Andrej

  • Anonymous
    April 22, 2010
    Hi, I am not able to extract the value present  in the textarea (multiline text ). Help please!!!!!

  • Anonymous
    May 11, 2010
    I have created a Parent / Child list releationship on a modified DisplayForm and also then used the above code in a CEWP on an EditForm for the adding new items to the child list. I found a good series of videos on the subject here... http://www.endusersharepoint.com/2009/12/10/creating-a-sharepoint-list-parentchild-relationship-%e2%80%93-video-remix/ One question though, will a site using these techniques backup & restore ok? I created a backup of my site, but when I restored it the associated “children” aren’t displayed on the “parent” form (the webpart gives a “non-specific” error), and also the “create new child” page which magically inserts the FK won’t display either…. any ideas why? I was using backup/restore in SP Designer to create a copy of the site. I also used Save Site as Template method and also export as Personal Webpackage method these also resulted in similar errors

  • Anonymous
    July 19, 2010
    Hi, Can't get it working because of ShowDropdown function ... error "object excepted". Any ideas? Thx.

  • Anonymous
    July 22, 2010
    I'm not sure if this was already mentioned in the comments - didn't feel like browsing through 11 pages of them to find out.  But I wanted to mention how to use getTagFromIdentifierandTitle to find a Date Picker field: getTagFromIdentifierandTitle("input", "DateTimeField_DateTimeFieldDate", title); So the identifier in this case is "DateTimeField_DateTimeFieldDate", tagName "input". Thank you very much for this code.  It was extremely helpful in getting a "populate today's date when empty" function working on a Sharepoint form. :)

  • Anonymous
    August 17, 2010
    Well, I struggled to get this working for a while only to realize my link is passing the display value rather than the ID # of my lookup item. While I am looking for a way to pass the ID in my URL, anyone have a clever method to translate the lookup Value - ID?

  • Anonymous
    August 30, 2010
    Thanks for the code. You said that field manipulation can be done using browser UI with formulae including today's date. I do not know how it works with today's date.

  • Anonymous
    May 23, 2011
    Great post... Looks like the identifier for MultiLine Text mentioned above is incorrect. It should be "TextArea" instead of "TextField".

  • Anonymous
    June 14, 2011
    Great post! Yo also have this framework that work fien in both scenarios (less and more than 20 items): cascadefilterlookup.codeplex.com JQ (blogs.solidq.com/sharepoint)

  • Anonymous
    June 29, 2011
    When the lookup field item count exceeds to 20 items, it is rendered as different control and setLookupFromFieldName method throws "object expected" error. Use following updated method to resolve this issue. function setLookupFromFieldName(fieldName, value) {         if (value == undefined) return;         var theSelect = getTagFromIdentifierAndTitle("select","Lookup",fieldName);         if (theSelect == null) {              var theInput = getTagFromIdentifierAndTitle("input","",fieldName);              document.getElementById(theInput.optHid).value = value;                       } else {              setSelectedOption(theSelect, value);         }    } This code works for me as i have to set lookup field programmatically and my lookup field on form is hidden.

  • Anonymous
    August 09, 2011
    Thanks for this tip, it saved me a lot of time and left the customer happy. I wrote a little article about manipulating Multiply Choci field biztoolblogs.tumblr.com/.../using-javascript-to-manipulate-a-multiply-choice-field

  • Anonymous
    December 06, 2011
    Hello, Can I use getTagFromIdentifierAndTitle to get a read-only field ? .. I have a custom page with a read-only field and would like to get that value so I can pass it to a caml query. Any help would be greatly appreciated. Thanks, KP

  • Anonymous
    March 22, 2012
    I want to know the identifier for a choice checkbox? Can someone suggest please

  • Anonymous
    August 09, 2012
    its fine. But i am just thinking of what value should I specify in <<QUERYSTRING VARIABLE NAME>>. Can you please explain it?.

  • Anonymous
    August 14, 2012
    The comment has been removed

  • Anonymous
    October 11, 2012
    Nice post ! Thanks!

  • Anonymous
    December 11, 2012
    Try using Kaldeera Forms www.kaldeera.com

  • Anonymous
    January 29, 2013
    Hi Rob, I have two datetime column type(say 'Business PVE' and 'Proposed Date For Go-Live').Now my requirment is 'Proposed Date For Go-Live' should'nt be earlier than 'Business PVE'..for that i have written client side code using j-Query in SP Designer.the codes are below.for the below code i get error as  'parentNode' is null or not an object...and when i put alert(control); its returning me null..I dont know why this is happening and what's the problem..pls help me out Rob... <script type="text/javascript"> _spBodyOnLoadFunctionNames.push("hideFields"); function hideFields() { var control = getTagFromIdentifierAndTitle("TAGNAME","IDENTIFIER","FIELD NAME"); //alert(getTagFromIdentifierAndTitle); alert(control); control.parentNode.parentNode.parentNode.style.display="none"; //alert(control); } 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 PreSaveAction() { var date1 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Business PVE");      var date2 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Proposed Date For Go-Live");    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)    {        alert("The Proposed Date For Go-Live cannot happen earlier than the Business PVE");        return false; // Cancel the item save process    }    return true;  // OK to proceed with the save item } </script>