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

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

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

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

  4. Dion says:

    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!

  5. Sean says:

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

  6. Suhaib says:

    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.

  7. Sharepointer says:

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

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

  9. rsriram22 says:

    Aha … A post on what I was looking for.

  10. Chad says:

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

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

  12. René Hézser says:

    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é

  13. David says:

    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.

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

  15. Marc (the netherlands) says:

    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

  16. rsriram22 says:

    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)

  17. Belchski says:

    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

    }

  18. Tom Byrnes says:

    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

  19. Jason says:

    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

  20. Patrik says:

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

  21. Jeff K says:

    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

  22. Matt says:

    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.

  23. Patrik says:

    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?

  24. Phani says:

    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.

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

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

  27. nevillew says:

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

  28. Tobias says:

    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.

  29. nevillew says:

    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…

  30. TracyW says:

    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

  31. Tom Resing says:

    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.

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

  33. cnovaksmart says:

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

  34. Tom says:

    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

  35. Jonathan says:

    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.

  36. Ben says:

    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

  37. Geoff G says:

    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>

    ———————————————————————-

  38. Skullcrusher says:

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

  39. GirlGeek says:

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

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

  40. jules says:

    hi,

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

  41. Tim Staddon says:

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

      }

    }

  42. echef says:

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

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

  44. buggsy2 says:

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

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

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

  47. RamUday says:

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

  48. RamUday says:

    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

  49. Sharon says:

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

    Thanks.

  50. Minou325 says:

    Does anyone know the identifier for a HiddenField?

  51. Markuso says:

    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&gt;

  52. Markuso says:

    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/

  53. T. says:

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

  54. Matt says:

    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”;}

    }

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

  56. singh30oct says:

    Hi

    can you send me some code

    any user create only 1 item in lookup kist box

  57. Matt says:

    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.

  58. Marius Mans says:

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

  59. sanjaya says:

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

  60. Ramadan says:

    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

  61. Lyndon says:

    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!

  62. chuasteve says:

    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.

  63. dosboy says:

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

  64. Troy says:

    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

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

  66. jjthomas says:

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

  67. frikouflios says:

    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

  68. jjthomas says:

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

  69. ronald says:

    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

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

  71. Soudip says:

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

  72. Skullcrusher says:

    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

  73. mani says:

    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

  74. sukebeta says:

    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;

    }

  75. Monty says:

    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

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

  77. ashishkanoongo says:

    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.

  78. dolomite says:

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

  79. dolomite says:

    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>

  80. WW says:

    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.

  81. Rajesh says:

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

  82. Candace says:

    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.

  83. Candace says:

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

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

  85. Swathi W says:

    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: "\pbosfile06policyApplication" 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()

  86. Chris says:

    Hi,

    What is the tagname for a person/group?

    Thanks

    Chris

    sammutchris@hotmail.com

    sammutchris@gmail.com

  87. Bobby Vastakis says:

    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

  88. bob e says:

    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

  89. bob e says:

    fty – That line in my core.css is:

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

  90. Tibor says:

    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?

  91. Eduardo Dias says:

    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

  92. cristina says:

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

    regards,

    Cristina

  93. Tuesday says:

    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!

  94. Jean says:

    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.

  95. Javier Regusci says:

    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.

  96. realite says:

    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

  97. Michael Hill says:

    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.

  98. Ramesh Krishnan says:

    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

  99. sandy says:

    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&quot; 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?

  100. tom daly says:

    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.

  101. SP Designer says:

     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

  102. Rob says:

    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.

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

  104. Parth says:

    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

  105. alienout says:

    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

  106. Rennick says:

    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

  107. sellwong says:

    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;

    }

  108. sellwong says:

    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

  109. Pradeep says:

    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;

       }

  110. Mark Stokes says:

    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&quot; 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&quot; 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

  111. Socki says:

    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

  112. Getto says:

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

  113. Frank_W says:

    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

  114. Bill Koontz says:

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

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

  116. Andrea says:

    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!

  117. gitz says:

    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

  118. Jeff says:

    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!

  119. Andrea says:

    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!

  120. Andrea says:

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

  121. Johnny says:

    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!

  122. Mary Kay Scott says:

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

  123. Rahul says:

    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&quot; /><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&quot; /></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

  124. Sam says:

    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

  125. Sam says:

    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>

  126. Adam says:

    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?

  127. Adam says:

    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.

  128. Jason G says:

    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!

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

  130. Mark N says:

    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?

  131. Tom says:

    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?

  132. Mauricio says:

    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…

  133. James says:

    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

  134. vj says:

    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

  135. willhlaw says:

    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>

  136. ashiena says:

    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…

  137. Philipp says:

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

  138. Shahab says:

    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

  139. samuel says:

    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

  140. Sri says:

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

    thanks

    srikanth…

  141. PrashanthSpark says:

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

    can i use PreSaveItem() function ?

    Please let me know.

  142. vaishnavi desai says:

    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,

  143. Andrej Dahllöf says:

    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

  144. Kiran K says:

    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.

  145. Bob says:

    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

  146. Brandon says:

    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?

  147. Roland says:

    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…

  148. Paul says:

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

    }

    }

    }

  149. Andrej Dahllöf says:

    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

  150. sujeet says:

    Hi,

    I am not able to extract the value present  in the textarea (multiline text ).

    Help please!!!!!

  151. Steveep says:

    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

  152. ian.stepanov says:

    Hi,

    Can't get it working because of ShowDropdown function … error "object excepted".

    Any ideas? Thx.

  153. Matt Kellner says:

    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. :)

  154. Caspur says:

    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?

  155. Tina says:

    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.

  156. Mujir Haniff says:

    Great post… Looks like the identifier for MultiLine Text mentioned above is incorrect. It should be "TextArea" instead of "TextField".

  157. JQ says:

    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)

  158. Ali says:

    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.

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

  160. KP says:

    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

  161. Santhan says:

    I want to know the identifier for a choice checkbox? Can someone suggest please

  162. Thrilendra says:

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

  163. Hassan says:

    really thank you i want this to be acheef, but unfurtinatly i cant acheef it , the code is complecated with me.

  164. Pedro Castro says:

    Try using Kaldeera Forms

    http://www.kaldeera.com

  165. Dave Milner says:

    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>