Get or Set value for SharePoint field in NewForm, EditForm and DispForm (Get only in DispForm)

Change log
August 19. 2013
Updated to v1.17 of spjs-utility.js


21.03.2011 Fixed a bug in setFieldValue on “over 20 items single lookup”.


14.06.2010 Updated the function “getFieldvalue” to fix a bug when returning the value for an enhanced rich text column on page load. Thanks to Kat for finding the bug.


This article describes how to get or set the value for all standard SharePoint field types in in NewForm, EditForm and DispForm (Get only in DispForm). This solution is tested in IE8, Firefox 3.6.3.

Instructions for getFieldValue

The function “getFieldValue” takes four arguments:

  • fin: FieldInternalName of the field to set the value for.
  • dispform: true if used in DispForm. Defaults to false if omitted.
  • multiValueJoinBy: String to insert as separator between multiple returned values. If omitted, separated by a comma.
  • optionalFilter: Used for “SPFieldUser” and “SPFieldUserMulti” only. If set to “displayName” or omitted, returns the displayName for the user(s), if set to “loginName”, returns the loginName for the user(s).

getFieldValue – example code in CEWP placed below the form:

<script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../../Javascript/spjs-utility.js"></script>
<script type="text/javascript">
fields = init_fields_v2();
// Get the loginName from a people picker
var myPickerVal = getFieldValue('MyPeoplePicker','','; ','loginName');
alert(myPickerVal);
// Get value from a multiline textfield
var myRichTextValue = getFieldValue('MultiLineRich');
alert(myRichTextValue);
</script>

Instructions for setFieldValue

The function “setFieldValue” takes three arguments:

  • fin: FieldInternalName of the field to set the value for.
  • newVal: the new value.
  • onLoad: true or false to indicate whether the value is set on page load. Default value if omitted is true.

To set the value you specify the new value in the parameter “newVal”. The following fieldTypes require some extra formatting on the parameter “newVal”:

  • SPFieldMultiChoice: “newVal” is a array containing the values to select.
  • SPFieldUserMulti: “newVal” is a string with the names (LoginName, DisplayName or Email-address) separated by a semicolon (;).
  • SPFieldLookupMulti: “newVal” is a array containing the values to preSelect. Note: Setting this field is only supported onLoad.
  • SPFieldBoolean: Set to true by passing 1,”1″, or true in newVal.
  • SPFieldURL: “newVal” is a array containing the URL and the description for the hyperlink.
  • SPFieldDateTime: “newVal” is a array containing the date, the hour (with AM/PM), and the minutes. Specify only the parameters to set (for date only, add only one item to the array).

setFieldValue – example code in CEWP placed below the form:

<script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../../Javascript/spjs-utility.js"></script>
<script type="text/javascript">
fields = init_fields_v2();
// Set the value for a radio buttons select
setFieldValue('MyRadioButtons','Radio choice nr. 2');
// Set the value for a date and time field
setFieldValue('MyDateTime',['5/28/2010','9 AM','25']);
</script>

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.4.2.min. If you download another version, please be sure to update the script “src”.

Read here how to add a CEWP to the NewForm or EditForm and how to find the FieldInternalName of your columns.

Sourcecode for “spjs-Utility.js”:
Download here

Save as “spjs-utility.js”, mind the file extension, and upload to the scriptlibrary as shown above.

Ask is anything is unclear.

Alexander

263 Comments on “Get or Set value for SharePoint field in NewForm, EditForm and DispForm (Get only in DispForm)

  1. Hi Alexander:
    I need some early morning clarity.

    To set the value in a multi-line text field, is this correct?

    // Set the value for a radio buttons select

    6 setFieldValue(‘MyMultiLine’,’PlaceValueHere’);

    Thanks

    Charlie Epes
    Buffalo, NY

    1. Hi,
      Like this:

      <script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript" src="../../Javascript/spjs-utility.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      // FieldInternalName is "MultiLinePlain"
      setFieldValue('MultiLinePlain','My custom value');
      </script>
      

      Alexander

  2. Hi,

    It seems that the getFieldValue returns blank for multiline rich text fields (correct value for plain text).

    The setFieldValue works fine for this type of field.

    Thanks in advance,
    Kat

  3. Hi Alexander,

    Thanks for sharing with the community.

    Could you do your “magic” by adding this type of field to your code: SPFieldHTML ?

    Thanks again,
    Jo

    1. What kind of field is this? a custom field? – the built in HTML-fields “Enhanced Rich Text” and “Rich Text” both have the type “SPFieldNote”.

      Alexander

  4. Alexander,

    Could this be used to display a total of three currency columns as the user is filling out the new/edit form of a custom list?

    1. Hi,
      I’m not sure if i understand this question… What about a calculated column to achieve this?

      Of course you could pick up the values in the function “PreSaveAction” and write them to another field, but please describe your requirement in more detail.

      Alexander

  5. Yes I agree, the calculated column is really what they should be using, butthey want it to act like a cell in excel that sums as the values are entered into the form. I am trying to get them to use the regular calculated column and just wait till they save saved the form to see the total.

  6. Hi Alexander

    I have a NewForm customized, the only difference from the original, is that i edit the default form(hide the default content) and add the correspondent customized list on the form and arrange the layout (i put some SPFieldText fields side by side like a matrix and remove the labels ).
    I know that “spjs-Utility.js” don´t work with costumized forms, and i have to edit the “init_fields_v2()”.
    Could you help me with a start point, how to get the “objects” in the init_fields_v2 .
    I have already read your post “How to use these scripts in a customized form” but i don´t have a clue how to “objectify” the fields.

    Thanks

    1. Hi,
      To make the init_fields_v2() work you will have to find something to identify the “fields” with. The original script uses “td.ms-formbody”, but you will have to find something else. Try adding your own class or some ID starting with a known prefix that you can search for.

      One thing to note is the fact that the original form has one field per <TR> and therefore makes an “object” containing the full <TR>.

      If you add more fields to one <TR> you will have to take this into the equation when creating the new function…

      I have another concern however, the spjs-utility uses the parameter “FieldType” from the original fields “description” tag.

      <!-- FieldName="Title"
          FieldInternalName="Title"
          FieldType="SPFieldText"
      -->
      

      You would have to either replicate this info tag or change the script to read this attribute elsewhere.

      I hope this helps – if not get back to me.

      Alexander

    2. Thanks for the quick response.
      I´m a begginer with jquery and DOM…
      Let me see if i Understand.
      For example, if i put a div with a classname and the “SharePoint:FormField ” inside the div.

      The way to get the values should be
      [

      $(“div.classname”).each(function(){
      var myMatch = $(this).html().match(/FieldName=”(.+)”s+FieldInternalName=”(.+)”s+FieldType=”(.+)”s+/);
      ….
      ]

      and replicate the info tag inside the div after the “SharePoint:FormField ”
      I really don’t know if “div.classname” is the correct form to get the information inside the div.
      I’am i right or completely wrong?

      Thanks again.

    3. Hi,
      Email me the HTML for your form, and i will take a look at it.

      Because you have variable colspan in the form (fields side by side) you must incorporate some extra logic to make full use of the init_fields_v2-function.

      Alexander

  7. I’m trying to get this to work with a multi lookup field but it doesn’t seem to work.

    when it was a single lookup it worked perfectly, but then i changed it to multi lookup and now it wont work.

    i’ve added a function to the onload to add these values. that’s the right way right?

    if i want to add 1 value its just

    setFieldValue(‘field’,’value’);

    please help,

  8. Hi – I am not sure why this isn’t working for me.
    Is there any way I can send you my source code? I am just working on a little test page, nothing major.
    thanks
    Amy

  9. Hi,

    Im trying to make small script based on this script to set value to dropdown in custom form, but i miss something … im not a pro in scripting, especially in jquery 🙁

    So my script is :

    var p = $(“:input[title=’field name’]”);
    var newVal = ‘value’;

    p.find(‘select option’).each(function () {
    if ($(this).text() == newVal) {
    $(this).attr(‘selected’, ‘selected’);
    }
    else {
    $(this).removeAttr(‘selected’);
    }
    });

    Ok, i’ve got pointer to field, it’s seems ok. But “each” function returns no items, so nothing happens in cycle.

    Thx for help 🙂

  10. Oh, solved by using p.val (‘value’); Everything was simply 🙂

    Btw,
    thanks for Your work, this scripts are really cool and helpful!

  11. I have one thing to ask….Can we set the value of Look up field in NewForm.aspx dynamically , I mean using session or query string.

    I have another custom control that will generated a value and that value i have to show as selected in look up column of New Form

    1. Hi, This “generated value” – is it available as a javascript variable?

      If so, it would be easy to “put” it in place using the PreSaveAction function.

      Ask again if this is unclear.

      Alexander

  12. Hi,
    Thank you so much for your reply.

    ‘the generated’ value is a selected Item of a drop down but i can make a javascript variable for that value.

    Can you please provide me a sample code for ‘How to use PreSaveAction’, it will be more helpfull

  13. Hi,
    Let me explain what i have to do.

    I have one drop down at home page which is a custom web part.User will select a value and that value i want to redirect to NewForm.aspx.

    I have created a session at home page but I am not able to use session with Javascript in NewForm.aspx.

    this Post is helpfull if i have default data to show as selected in the field but i need a dynamic approach to make it happen.

    Thanks

    1. Hi,
      If you could include the selected value in the URL to the NewForm like this:
      …/NewForm.aspx?MyCustomvalue=Some text her from the select on the front page.

      Then you could “pick” the value down from the querystring part of the URL and set the field in NewForm.

      Alexander

  14. I have a question (sorry I’m a noob)

    But if I want to automatically set a value for a people picker with the person’s name that is logged in making the request (basically the ‘Created By’ value) how can I do that?

  15. Hi,
    I have a NewForm.aspx and I have fields With the name CustomerID and it is Number Field I had tried a lot but some how i am not able to set the Field Value.

    May Javascript Refrence i have Placed wrong but i have put the JScripts in Layouts Folder
    PLease guide me
    Thanks
    Parth

  16. Thanks for getting back to me – rarely use JS so always rely on others expertise like yourself!

    …I only get the link text as far as i can tell.

    What sort of java object is returned for SPFieldURL? It might just be I need to get the anchor’s href property, .href?

    Once again, a most invaluable script.

  17. Great script and this is very helpful, but I am running into one issue and would appreciate some direction. There is a people picker field that I am using the getFieldValue for (in the PreSaveAction function) and I am setting a hidden text field with the display name from this field so I can send a workflow email with the display name rather than Domain/user. This works great if the person is validated before the form is submitted, but if they just type the name and submit the form, the value I get is blank because apparently getFieldValue is executing before the person is validated and the people picker field is set. Any ideas on how to work around this?

    1. Hi,
      You could set a function to trigger on the “blur” event to validate the input by #clicking” the “validate user image” when focus is taken away from the people picker. Let me know if you need help on this. I’m a bit busy, but post a replay here and i will give you an example.

      Alexander

  18. Ta – alerts were how I started to see all the values. The alert shows the text value only – no hyperlink and it’s not ‘clickable’ in the alert box.

    Regards, Mike.

    1. Hi,
      It sounds sort of strange – look at line 233-236 in the script and see what you make out of it. The default behavior is to return a normal <a href=…

      Alexander

  19. Hello, your site has been very helpful to me so far but I have run into a problem that I can not figure out and was hoping that you or one of your readers could lend a hand. What I am trying to do is build a table in javascript to place into an enhanced rich text edit box. The headers for this table are based on a comma separated list in another text input field. I have a function that gets attached to the text input’s onkeyup event. So the problem that I am having is that in IE when the function runs it uses setFieldValue() to set the content in the ERT area but doesn’t actually show up. In firefox the text shows up fine. In IE the text is being set but it doesn’t actually show in the ERT area. Any thoughts?

    1. Hi,
      To have the value set after the initial page load, you must set the argument “onLoad” to false like this:

      function setRTEcontent(){
      var tableBuffer = [];
      	tableBuffer.push("<table style='width: 100%'>");
      	tableBuffer.push("<tr>");
      	tableBuffer.push("<td>Heading 1</td>");
      	tableBuffer.push("<td>Heading 2</td>");
      	tableBuffer.push("</tr>");
      	tableBuffer.push("<tr>");
      	tableBuffer.push("<td> </td>");
      	tableBuffer.push("<td> </td>");
      	tableBuffer.push("</tr>");
      	tableBuffer.push("</table>"); 
      
      	setFieldValue('MultilineEnhanced',tableBuffer.join(''),false);
      }
      

      You must call the function “setRTEcontent” to have it set the value for your field – mine has a FieldInternalName of “MultilineEnhanced”.

      Alexander

    2. Hi,
      A little update on how to dynamically set the value of a TD with a specific ID attribute – works only in IE though:

      function setRTEcontent(){
      var tableBuffer = [];
      	tableBuffer.push("<table style='width: 100%'>");
      	tableBuffer.push("<tr>");
      	tableBuffer.push("<td>Heading 1</td>");
      	tableBuffer.push("<td>Heading 2</td>");
      	tableBuffer.push("</tr>");
      	tableBuffer.push("<tr>");
      	tableBuffer.push("<td id='myFirstTD'></td>");
      	tableBuffer.push("<td></td>");
      	tableBuffer.push("</tr>");
      	tableBuffer.push("</table>"); 
      
      	setFieldValue('MultilineEnhanced',tableBuffer.join(''),false);
      
      }
      
      function setValInTableWithinRTE(id,val){
      	$(fields['MultilineEnhanced']).find('iframe.ms-rtelong').contents().find('#'+id).append(val);
      }
      
      

      You must first call the function “setRTEcontent” to insert the table, then call the “setValInTableWithinRTE” with the ID and the text to append.

      Alexander

    3. Is there any way that I can build a table in an enhanced rich text edit box using CEWP? If so would you please send me or post the code?
      Thanks in advance

  20. Having trouble retreiving data from the DispForm by using the getFieldValue
    () function. Keeps on returning undefined for any field i’m trying to get data for. Using similar code to the example above :
    fields = init_fields_v2();
    var titlename = getFieldValue(‘Title’);
    alert(titlename);

    Any reason for why they may be happening?

  21. Hi Alexander,

    Thanks for your response. I did add the extra argument to the function but it is still returning an undefined.

    After inspecting the source of the DispForm, do see where the values for Display Name, FieldInternalName, and FieldType are being rendered, however they are enclosed in an HTML comment tag. Could this be causing the problem?

    thanks

  22. Hi Alexandr, thank you for your great posts! I’m new to JS and use it for MOSS design.
    I try to use your function in order to get/set Yes/No field in Edit form, but I got an error that the function is expecting the object.
    I use it as follow:
    var L = getFieldValue(‘LFM’);

    while LFM is my column display and internal name..
    Hope you can help and it’s clear enough.
    Thank you!

    1. I solved it by using your other function:
      getTagFromIdentifierAndTitle(“input”, “”, “LFM”).checked = false;
      or
      getTagFromIdentifierAndTitle(“input”, “”, “LFM”).checked = true;

  23. I am just getting back. I saw your response to my other request and will follow up on that one soon. With this script I have 3 dates fields. I would like to calculate the third friday of the month, and use that variable to populate the first date field.
    I know the population is simple. For now I am doing this:
    var friDate = ‘1/15/2011’;
    setFieldValue(‘FridayBegin’,[friDate,’6 PM’,’30’]);

    I have this code to calculate the third friday, but it does not seem to fire
    [sourcecode]
    function showThirdFriday(){

    tFriday = new Date();
    tFriday.setDate(1);
    // Find first friday.
    while( tFriday.getDay() != 5){
    tFriday.setDate( tFriday.getDate() + 1 ) ;
    }
    // Add 2 weeks.
    tFriday.setDate( tFriday.getDate() + 14 );
    alert("Third friday this month " + tFriday);
    }

    How can I get this or a similar function to calculate the third friday, then use this variable in the setfieldvalue?

    thanx

    1. Hi,
      If the data is visible in DispForm, it is possible. My problem is that i do not know what kind of field it is. Have you checked the fields “FieldInternalName” and tested the getFieldValue-function?

      Alexander

    2. Yes I can see the FieldInternalName but I get the custom error message that reads

      Unknown fieldType: “SPFieldBusinessData”, please ensure you use the function init_fields_v2

    3. If you use the code in dispForm this should not matter. Did you set the parameter “dispform” to true? -like this:
      getFieldValue(“MyFieldName”,false);

      Alexander

  24. I am trying to fire the “Add>” button event using java script for the share- point “SPFieldLookupMulti” control, I need to do this to re-order the list items on the right of the control on page load (using jquery’s) document ready() function.. Any Idea’s?

    Thanks

    1. Like this:

      fields = init_fields();
      $(document).ready(function(){
      	$(fields['MultiLookup']).find(':button:first').click();
      });
      

      My multiLookup is named “MultiLookup” – replace with your FieldInternalName.
      You must use the function init_fields() from the article.

      Alexander

  25. Thank you for all your wonderful additions to the SharePoint community.

    I have a quick question. Can you please help with passing values from the query string into the “newVal” variable?

    I would like to use this to dynamically set the values on the new form depending on the query string.

    Thanks again!
    Mark

  26. Alexander,
    Thanks for the quick response. I apologize but I’m a newbie here. Can you please walk me through where to place the GetUrlKeyValue?

    Thanks!

    1. Lets say you have an URL query string like this:
      …Lists/MyList/NewForm.aspx?myVar=here is my new value

      <script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript" src="../../Javascript/spjs-utility.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      // Set the value for a text field named "MySingleLineText"
      setFieldValue('MySingleLineText',GetUrlKeyValue("myVar"));
      </script>
      

      Alexander

  27. What I was missing from this senario was how the values were being passed form one form to the other – until I saw the URL Query String example. I’ve tried many code examples and this is the first to successfully populate a sharepoint foundation (2010) lookup field in the default new form. I have a problem in that I’ve had to import 5,000 records into a “company name” lookup column. I have no problem adding them to the query string, but many contain &, % and other symbols that complicate the extraction from the query string on the “populate” form. Is it possible to set these values to a global variables on the “get value” form and use the global variable to set value on the “populate” form. Maybe this would solve the problem of extracting values containing problem symbols that break the extract from URL query string process.

  28. Alexander,

    Great post! One question though, how would I get the value for SPFieldMultiChoice onchange event? I’m using your code, with other code, to hide certain fields based on the value of the SPFieldMultiChoice. So I need the fields to appear and disappear when the user clicks any of the SPFieldMultiChoice values. Any help would be greatly appreciated!

    1. Hi,
      Sorry for the late reply. Only fields rendered in the page (and hidden using JavaScript). Fields hidden in the list settings are NOT rendered on the page, and therefore not available.

      Alexander

    2. The “hidden” fields would be available to you using a Web Service call, but you’ll have to write that data back to the list during your PreSaveAction(). Definitely a possibility though.

    3. Hi,
      If you write the data back in the PreSaveAction, you will get an save conflict when the save item is performed.

      For this to work, you would have to hijack the save process entirely and write all data using a webservice call and abort the “built-in” save item.

      Alexander

  29. I have really found spjs-Utility amazingly useful. Thanks very much for sharing it! I have a question on applying a value to a Sharepoint complex (greater then 20 items) lookup field. I have one lookup field and I wanted to have the choice in that field force a choice in the second lookup field. Unfortunately I can’t get a value to show up. The value would be one that is available in the second lookup. I noticed that you had an example of a multi-select lookup, but I’m working with just a single select.
    I have tried the following:
    setFieldValue(‘TherapeuticArea’,valTA);
    setFieldValue(‘TherapeuticArea’,[valTA]);
    setFieldValue(‘TherapeuticArea’,'[valTA]’);

    Thanks for any advice.

    1. Hi,
      It was a bug that is fixed now. The right syntax is the first example in your post above – if the valTA is a variable.

      Alexander

  30. Another great util! I am using a product call sharepointboost for column permissions that seems to keep me from being able to get the value of a column. It is rendered as a readonly column and i tried using the getFieldValue(‘myfield’,’true’) but still does not seem to get the value. I have also read about disabled vs. readonly columns….can your util accomodate my issue? Thanks!

    1. Hi,
      I do not know this solution, but i guess the problem has to do with the html rendering in the page missing the “comment tag” i use to identify the fields in the function init_fields_v2()

      If you cannot figure it out you can send me the html (right click and view source) and i will take a look.

      Please specify the column name so i know what to look for.

      You find my email here

      Alexander

    1. Hi,
      I think you could, but you have to use SharePoint Designer to add the script.

      Go to your WF folder, find the form created from your Workflow. Open it in SPD and add the script at the bottom – right before the </asp:content>

      EDIT: I was a bit quick there, the form is constructed i a different way and the init_fields function will not work. Look at the form and see what you make out of it. Let me know if you need any help piecing it together.

      Alexander

  31. I am quite new to Sharepoint and need some help. I am trying to do the following:

    I have a list called “Project Notes” that are related to parent list called “Projects” with the related field called “ProjectId”.

    I have setup a Related View inside the Project DisplayForm which displays the related Project Notes at the bottom.

    When I am inside the Projects DispForm , I’d like the ADD NEW button (for the Projects Notes Related View) to pass the Projects ProjectId to the “Proejcts Notes” NewForm and populate the ProjectId field.

    Is this possible and do you have some sample code to start with?

  32. Works on all fields except a Choice column in my 2010 Document library. I have a column name Doc Group which when I perform an alert returns undefined. I have another column named Opportunity which is a Site Column lookup and it works perfectly. I have tried:

    var dgValue = getFieldValue(‘Doc Group’);

    and also:

    var dgValue = getFieldValue(‘Doc Group’, false);

    Any thoughts? I want to grab this value to use during a PreSaveAction, but cannot get beyond this hiccup.

    Thanks,

    CDulany

  33. Hi alex,
    My understanding is that I only need to modify the code in the CEWP (i.e to pass my field name), but for some reason I can’t seem to get this work. I’m using a custom SharePoint form that I want to set the value of a list item (drop down) field on. The internal name of the field is @My_x0020_Important_x0020_List_x0

    Any thoughts?
    Thanks,
    Nick

    1. Hi alex,
      Thanks for the reply. I took a look at it, but I’m still not sure where I need to make changes. Would I need to change the “spjs-utility.js” or the CEWP? I want to use the display name rather than making tagging custom ids. Any help would be great.

      Thanks,
      Nick

    2. So far I modified spjs-utility to replace the init_fields_v2() with what you have in your other post. I also added an ID to the TR tag of the formlabel field. I still cant seem to get it working. I’m sure I’m missing something stupid. 🙂

    3. Sorry for the extra replies. I made some progress and now I’m getting an alert window saying “the attribute “FieldType” is missing. Ensure that you use the function init_fields_v2().

    4. Hi,
      Sorry for the delay. You are on the right track, but you did not have to replace the init_fields_v2() in spjs-utility.js. You call the function from the form using:
      fields = init_fields_v2()

      You could make a new function “locally” and call it like this:
      fields = custom_init_fields()

      The getFieldValue and setFieldValue functions need the field type to know what to do. Your custom init_fields-function must add this attribute to the “fields-object”.

      Alexander

    5. Thanks for the reply Alex. I figured that was the issue, unfortunatley, I couldnt get the fields object to be passed from the code in the CEWP. I was however able to modify the spjs-utility.js to temporarily hardcode the field type (since right now im only using it for choice fields), but that will only work for my current use case. Would you be able to provide the code i need in my CEWP to get this working? Thanks again for your help.

  34. Hi, Alex.
    Can i get the user ID from SPFieldUser type field? I need it to perform a search on list using SPQuery (“DisplayName” can be duplicate!).

    1. Hi, You cannot always find the userid in the peoplepicker. I would recommend using the loginname and do a lookup in the userlist to find the id.

      Let me know if you need any guidance.

      Alexander

  35. Hi Alexander, i have found your plugin very helpful on SharePoint 2007.. But i am having a bit of trouble on SharePoint 2010 enhanced rich text box’s.. Sorry im a bit of a noob when it comes to javascript but it seems the way ERT boxs work differently from 2007.. they no use iframes although standard rich text boxs do..

    Heres the generated HTML for the ERT field…
    [CODE]

    Rich text editor

    !!!!!!!!!!THE ENHANCHED RICH TEXT EDITOR CONTENT HTML!!!!!!!!!

    [/CODE]

    The Bit i want to set goes where i put… !!!!!!!!!!THE ENHANCHED RICH TEXT EDITOR CONTENT HTML!!!!!!!!!

    The bit of jQuery i use to fill this area is: [CODE]$(‘div.ms-rtestate-write.ms-rteflags-0’).html(tmHTML);[/CODE] which is a bit cheap but it works and probaly will for only one ERT box on the page..

    I was just wondering if you had a simple workaround to use your plugin on these… Thanks Tony

  36. Hi
    Is it possible to use java script to copy and paste data from a single line text to another single line text based on chaise field in Edit Form.

    Column A Column B Choise
    Hi No
    Hello Hello Yes

    Means When user Edit Data in the Edit Form When the select Column Chaise Yes the system Copy Value of Column A to Column B.

    I can do it using work flow but do not want to use it. User prefer doing it while they do in the Edit Form

    Thanks in advance

    1. Hi,
      Yes, do something like this:

      function PreSaveAction(){
        var triggerVal = getFieldValue('putChoiceColumnFieldInternalNameHere');
        if(triggerVal==='Yes'){
          setFieldValue('ColumnA',getFieldValue('ColumnB'));
        }
        return true;
      }
      

      This code will copy the value from ColumnA to ColumnB when saving the form.

      Alexander

  37. Great post Alexander.

    Is it possible to use/modify this apporach to reset fields to their default values (that is, the default field values for a new item)?

    thanks,
    Bruce

    1. Hi,
      This script does not know the default value – it is stored in the list schema and must be obtained by a webservice query.

      Can you clarify a bit more the scenario?

      Alexander

    1. Hi,
      There is a known issue with checkboxes in jQuery 1.6.x.

      Is it the checkboxes that are the problem?

      I will update the solution with a fix as soon as i get your answer.

      Alexander

  38. One thing that annoys me about SharePoint Discussion Boards is that it appends the message of the discussion in the Body MultiText Field on Reply. Could this method be use to clear that text and add something else like “submit your reply”? Or do you know a method to achieve this? Any help would be appreciated.

    Regards,
    ink

  39. I’m trying to retrieve the value of a Person or Group field in EditForm
    and NewForm (ideally the user.ID) at onload or onchange to set
    on the fly other text fields in the same form (email, login).
    How can I do that ? The following code is not working:

      // Onchange
      fields = init_fields_v2();
      $(fields['RequestedBy']).find('input').change(function(){
        var requester = $(this).find('input').text();
        var ui = getUserInfo('requester'); // requester is a string not an ID ?
        alert('requester : ' + requester + ' => ID = ' +  ui.ID);
        setFieldValue('User_x0020_mail', ui.EMail);
        setFieldValue('User_x0020_login', ui.Name);
      });
      // Onload ??
    
    

    Thanks in advance

  40. I have run across an issue where if the fieldname has spaces in it, then I am unable to retrieve nor set any field values. After spending some time, I have found that it my issue appears to be in the function init_fields_v2() code where you build the res object through the following code:

    res[fin] = this.parentNode;
    $(res[fin]).attr(‘FieldDispName’,disp);
    $(res[fin]).attr(‘FieldType’,type);

    One of the things that I’ve noticed w/ SharePoint is that if the field is set up initially without a space, the developer can then modify the name of the field to have a space but SharePoint keeps its original internal name. If the field is set up initially set up with spaces, then SharePoint converts each space and replaces it with “_x0020_” and if the developer then changes the ‘display’ name to not have any spaces in it, then once again, SharePoint keeps the original internal name. I haven’t tried it yet but I’m guessing that after the list field is initially created, then the developer can change the ‘display’ name to whatever he/she wants but the internal name won’t change with it (unless one completely deletes the list field and re-creates it from scratch).

    Now, as I’m *REALLY* lazy and don’t want to have replace all the spaces with “_x0020_” when I call getFieldValue and setFieldValue, nor do I want to have to view source on the form to find out what the ‘real’ internal name is for each field on the form, do you think that the following modification to your code would be ‘safe’ to do?

    res[disp] = this.parentNode;
    $(res[disp]).attr(‘FieldDispName’,disp);
    $(res[disp]).attr(‘FieldType’,type);

    Basically, what I trying to do is set the ‘index’ to the display field name [disp] instead of the internal field name [fin].

    Your thoughts? … comments?

    Any prompt replies by you or anyone else in the SharePoint community would be most graciously appreciated.

    Many thanks in advance,

    Roy Higashi

    1. Hi,
      Though I think this would work i strongly recommend you to go with the proper FieldInternalName.

      This because the displayname could easily be changed by anyone with edit list permission and thus break your script. Another thing is SP2010 and multiple language packs – the displayname can be translated and again break your script.

      Read here how to find the FieldInternalName

      Alexander

    2. Hi Alexander,

      Thanks for the quick response. Yes, I thought about the edit list permission thing but I had forgotten about the language pack thing.

      For now, if there’s anyone going around mucking up the works, then that gives me a good reason for going after them with a *BIG* stick .

      Thanks again,
      Roy

  41. Alexander,

    How would you handle the ‘SPFieldTargetTo’ type? This is the type used for the ‘Target Audience’ field on a newform.

    Regards,
    Chuck

    1. Hi,
      I do not have access to a MOSS or SP2010 server and cannot test it. Look at the scripts and add an new “case” to catch your field type.

      Alexander

  42. Hey Alexander, Love this script. I saw the comment on the issue with checkboxes. Does that include dropdown fields? I have a choice field I am trying to set a value to but no mater what i set the newVal too it always selects the last item in the choice field. I am on SharePoint 2010 Enterprise.

    Thanks,
    Joe

    1. Hi,
      Not that i know of. Selecting the last sounds weird – the first would make more sense…

      Are you sure the value your try to set is a valid choice in the dropdown?

      Alexander

    2. in spjs-utility.js I commented out this line:
      $(this).removeAttr(‘selected’);
      and it started working fine – this is on the NewForm.aspx.

      Not sure how I’d deal with changing the choice once it’s set.

  43. Hello Alexander,

    Thanks for the SPFieldMultiChoice help.
    I present the problem now to revert does values, but when I pass ”,’0′ or ‘(none’) it just doesn’t uncheck the field.
    I have it working with single checks but with SPFieldMultiChoice and fields like a lookup I am able to set the value but, if I need to clear them to select another option it just doesn’t do it, any advice?

    Thanks a lot.

    Rafael

    1. Hi,
      Do it like this:

      $(fields['YourMultiChoiceField']).find('input:checkbox').prop('checked','');
      

      NOTE:
      You must use jQuery v1.6.x

      Alexander

  44. Hello Alexander thanks for all your answers, I have one more question regarding SPFieldChoice, It works great on radio buttons but in a drop-down menu, it just doesn’t do it, I checked the function and looks like it should work either way.

    Any idea? thanks a lot.

    Rafael

    1. Hi,
      A drop-down choice cannot be reset to a blank value when it has been saved with a non-blank value. This is built in and cannot be overridden unless you activate “fill-in choices”.

      EDIT:
      You could make a “workaround” adding a choice reading “<select>” as the first choice. Not the prettiest solution, but then you could at least reset the field.

      Alexander

  45. This looks fantastic. Only concern i have is it seems that for adding this JS on NewForm.aspx of list, you will need to manually modify the url (ToolPaneView=2) and add this JS in CEWP. But my problem is i have 40+ lists.

    is there any way in which this can be automated ( i don’t want to create a feature for list provisioning)??

  46. Hi,

    I am facing issue while setting value of Lookup field. It always changes to default value and desired value is not set.

    I dig into your js code and found following snippet in setfieldvalue function.
    case ‘SPFieldLookup’:
    thisField.find(‘select option’).each(function() {
    if ($(this).text() === newVal) {
    $(this).attr(‘selected’, ‘selected’);
    //ADDED RETURN FALSE HERE TO FIX IT
    return false;
    } else {
    $(this).removeAttr(‘selected’);
    }
    });
    break;

    i found that when desired value was found, still the loop was going on,hence again resetting the value. I have added return False when node is found to fix this.
    Let me know if you think this might have some other impact

    Amit

    1. Hi,
      Thank you for finding this bug – i have updated the solution with a slightly different method to prevent setting the last option when attempting to set an invalid value.

      Alexander

  47. Hi,

    I saw your post it looks Well I’m trying to set value for fields named “Request Status”(Dropdown, can have values as Approved,Pending,Rejected) and IsAppReq(Checkbox).
    Here are my questions:
    This i need to do this on Edit form. will this work on edit forms?
    If yes, could please me in writing the correct syntax for the two.

    Thanks for your help.

    1. Hi,
      The syntax for the select (dropdown) is:
      setFieldValue(‘FieldInternalName’,’the value’);

      And for boolean (Yes/No):
      setFieldValue(‘FieldInternalName’,1);

      Alexander

      1. Hi, Thanks for your last reply..it was really helpful. Now I have another doubt. Iam trying to set the dropdown value to a specific text(present in the dropdown values) on some condition. I am doing it in PresaveAction function. But the setFieldValue() isnt working for the dropdown. iam giving it in the correct syntax as below. I have used the spjs-utility.js aswell. Please help. Thanks in advance.

        setFieldValue(‘Application_x0020_Name’,’N/A’); //Application%5Fx0020%5FName

      2. Hi,
        The syntax is correct, and if your FieldInternalName is correct this should work.

        You are aware that setting the value in PreSaveAction will not kick in until you save the form?

        Could it be that you have multiple functions named PreSaveAction? – if so, only the last one will work.

        Alexander

  48. Pingback: Blog
  49. Thank you so much for posting this out on the web Alexander! This was exactly what I needed. I’ve run into one problem though that I’m hoping you can help me out with. I can’t seem to get the “getFieldValue” function to work for a multiple value lookup field on an edit form. I’m trying to use it like below, but it never it won’t retrieve any of the values.

    var impchnls = getFieldValue(‘Impacted_x0020_Channels’);

    1. If you try to get the calue on page load, you must wrap it like this:

      $(document).ready(function(){
      	var v = getFieldValue('MyLookup');
      	alert(v);
      });
      

      Alexander

  50. Hi Alexander, I hope you’re fine.

    In init_fields_v2() function, the variable “myMatch” always returns null.. I don’t know why !!. This kills the whole thing which leads to nothing actually. The field I target is not set. Please, help.
    Here’s a my code:

    $(document).ready(function()
    {

    fields = init_fields_v2();
    setFieldValue(‘Title’,’gym3′);
    //alert(‘done’);

    });

  51. Can this cold be modified to handle Infopath forms inserted as a web part in Sharepoint? It works for standard form such as dispform.aspx but I want the JQuery and SPJS-Utility to read values on displayifs.aspx.

  52. Hi Alexander.

    Thank you very much for your reply. The Answer is no, this isn’t a standard form this is a modified one. BTW, I’m working on SP 2010 does this make any difference ? cuz I’ve noticed that your code searches for elements with attributes like: (FieldType and InternalName) and I don’t find those attributes on my Fields. I only have a “<SharePoint:FormField … " with an attribute called (FieldName) holding the title of the field so I guess this what caused init_fields_v2 function to return null. This is bad, isn't it ? 🙁

    1. Hi,
      This solution (and all the other solution posted in this blog) requires the forms to be “out of the box” with no SharePoint Designer customization.

      You should give your fields an unique ID and use plain javascript to get the value as this solution relied upon the FieldType and InternalName to identify the type and nature of the field.

      Alexander

  53. Hi Alexander,

    first of all, thanks for this great work!
    It seems that taxonomy fields are not supported for setFieldValue though. I’m I missing something? If not can you update the code

    1. Hi,
      I do not have access to SharePoint sever and the taxonomy field are not part of SharePoint Foundation so I cannot tell if this works, but I do believe taxonomy fields are similar to lookup fields and thus you could add case:’SPFieldTaxonomy’: – or whatever the type is
      below case ‘SPFieldLookup’: to have this “case” catch both.

      Alexander

  54. Thanks for a great tool! Do you think that you may include date and time formatting in a future enhancement? There are some times when the month and day need to be padded, 01/05/2012 or the hour padded, 08:12 AM, or time in 24 hour format, 0812.

    1. This tool will return the value in the format it’s displayed in the input and the select controls. I’m not quite sure what you are asking? it it the leading “0”?

      Alexander

    2. Yes, I would like the date to be displayed a bit differently than what the input shows, like the leading 0’s or in 24 hr time format.

      1. You would have to manipulate the values after they have been retrieved using the getFieldValue function.

        Alexander

  55. Alexander,

    I am trying to validate that 2 different People Picker values are not the same on form submit. I am using the PreSaveAction and have tried many ways and always get “undefined”. Any ideas?

    1. I am getting back values from my var’s but when I use:

      if(group1 === group2){
      alert….
      return false;
      }
      return true;

      This is not working. Is there a filter I need to apply?

  56. Is it possible using this to get data from another list (List A) and set values in a newform in another list (List B) based on createdby (List A) is equal to current user (List B)?

  57. When I test getFieldValue and alert I only get “Undefined” ??

    Why..?

    My code:

    fields = init_fields_v2();

    var sValue1 = getFieldValue(‘Title’,’true’,’; ‘,”);
    alert(sValue1);

    Regards Henrik

    1. Hi,
      From the getFieldValue example you are presenting – it looks like you are using it in DispForm (the second parameter = true) – Are you?

      All but the first parameter is optional in NewFoem or EditForm.

      Alexander

    1. Hi,
      I’m on SharePoint Foundation and this does not have Managed Metadata fields. I do think they behave similar to lookup columns, so you could try adding another “case” to the script – below the “lookup case” – with the correct fieldType (look at the page source to find it).

      Alexander

    2. Thanks,
      I’m used this code but it doesn’t work with $(document).ready but when I execute the code with button in the page it work.
      because in the first time the div “div[id$=”editableRegion”]” doesn’t created.

      case ‘SPFieldTaxonomyFieldTypeMulti’:
      var editableRegion = thisField.find(‘div[id$=”editableRegion”]’);

      if (editableRegion.length > 0) {
      if (!editableRegion.find(‘span’).html()) {
      editableRegion.html(newVal);
      var taxonomyParent = editableRegion.parent().parent().parent();
      if (taxonomyParent.length > 0) {
      var taxonomyObject = new Microsoft.SharePoint.Taxonomy.ControlObject(taxonomyParent.get(0));
      taxonomyObject.validateAll();
      }
      }
      }
      break;

  58. Hi,

    Could you please suggest me , how to use getFieldValue for SPFiledBoolean . In my form I have 6 SPFiledBoolean columns. I am trying to get those values. Irrespective whether they are checked or not , it’s returning false.See the below script and suggest

    var actPrj=”;
    actPrj= getFieldValue(‘Act_x0020_Project’);
    alert(actPrj)

    1. Please find the below code. I am trying to get the value of yesno choice i.e SPFiledBoolean. But every time it’s returning false, even though it’s checked.

      function PreSaveAction()
      {
      var actPrj=”;
      actPrj= getFieldValue(‘Act_x0020_Project’);
      alert(actPrj)

      return true

      }

      1. Ensure you have the latest version of spjs-utility.is, and are using v1.6+ of jquery. Alexander

  59. Hi,
    in your utility, there is no implementation of function setFieldValue for type “SPFieldNote_EHTML”. Why? Is it possible to add it?
    Thanks for your effort.

  60. Hi Alex,

    I’ve tried this code numerous times with different fields and for the life of me I can’t figure it out why I can’t get the value to alert. The alert pops up, however nothing is in the alert.

    I am using a people picker with the FieldInternalName as Email_x0020_Name. The code I am calling is

    
    //var myPickerVal = getFieldValue('Email_x0020_Name','true','; ','displayName');
    //alert(myPickerVal);
    
    

    Obviously not commented though.

    It is being placed is DispForm, using jquery 1.7.2 and SP2007 and placed below the display table. The display name would have a space in it if that makes a difference (but I tried a single word in a text field and I get undefined). Fin is defined properly.

    Could it be that the alert appears before anything is displayed on the screen. In other words when I click the item to view in the list, the alert pops up blank and only after I click OK the display table appears. If that is the case not sure how to get around that.

    Any thoughts on this – anyone else having a similar issue?

    1. Hi Alex,

      Found the answer to this – jquery wasn’t referenced correctly go figure but works like a charm.

      Is there a way set the value of a field with the item’s [ID] number? I am trying to integrate this with your latest Dynamic Forms which doesn’t display calculated fields so just thinking of a workaround

  61. Hi Alex, I am trying to use your code with a radio button (Yes/No options) but have been unable to get it working. Neither the getFieldValue nor the setFieldValue are functional.

    I have my js file, along with jquery 1.8.0 and your js file all in the same folder on my site.

    I am trying to alert the value of my radio button then set it to be ‘Yes’. Here is the code I wrote:

    alert(getFieldValue(‘PhoneAtNewLocation’));
    setFieldValue(‘PhoneAtNewLocation’,’Yes’);

    Can’t figure out what’s wrong as it looks so straightforward! Any help you could provide would be greatly appreciated!

    Thanks!

    1. Yes the CEWP is below the form web part. I tried moving it to the top just now as a test but that gave the same ‘undefined’ error. I’m assuming it is supposed to be at the bottom so I moved it back.

      Here is the complete picture if it would help (minus the other js file references):

      $(document).ready(function(){
      fields = init_fields_v2();

      //Get all radio buttons, checkboxes, and drop downs from the page into an array
      var radioButtonsArray = new Array();
      radioButtonsArray = $(“.ms-RadioText”);

      //Add on click events to the Request Type radio buttons to hide/show user info rows based on user’s selection
      $(radioButtonsArray[0]).click(function(){
      $(‘.NewUserRow’).show();
      $(‘.ExistingUserRow’).hide();

      alert(getFieldValue(‘PhoneAtNewLocation’));
      setFieldValue(‘PhoneAtNewLocation’,’Yes’);
      });

      $(radioButtonsArray[1]).click(function(){
      $(‘.NewUserRow’).hide();
      $(‘.ExistingUserRow’).show();
      });
      });

    2. Hi,
      Do it like this:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
      <script type="text/javascript" src="https://files.spjsworks.com/files/spjs-utility/v1.11/spjs-utility.js"></script>
      <script type="text/javascript">
      var fields = init_fields_v2();
      
      var arrToToggle = ["MyField1","MyField2"];
      
      // Page load
      if(getFieldValue("MyChoice")==="Yes"){
      	$.each(arrToToggle,function(i,fin){
      		$(fields[fin]).hide();
      	});
      }
      
      // Click
      $(fields["MyChoice"]).find("input:radio").click(function(){
      	if($(this).next().text()==="Yes"){
      		$.each(arrToToggle,function(i,fin){
      			$(fields[fin]).hide();
      		});
      	}else{
      		$.each(arrToToggle,function(i,fin){
      			$(fields[fin]).show();
      		});
      	}
      });
      </script>
      

      Alexander

    3. I apologize I should have clarified more…the rest of the code I posted works perfectly fine. The click events are on one radio button, which hides and shows several other fields. The getFieldValue and the setFieldValue are attempting to work with a completely separate radio button and this is the only part where I’m stuck.

      I had tried getting the second radio button value by doing $(radioButtonsArray[2]).value; and $(radioButtonsArray[2]).attr(‘checked’); but couldn’t find a way to get that to work. Each time it came back with ‘undefined’ so that’s what caused me to seek out your code. Also, parsing the $(radioButtonsArray[2]).html(); for the “checked” value did not work because after the form loads, user input does not appear to change this html.

      Are the getFieldValue and setFieldValue functions not designed to work with radio button form fields?

    4. In that case you should use .prop(“checked”) and not .attr(“checked”).

      Please note that this is supported in jQuery v1.6x and above.

      Alexander

  62. Hi Alex! I have a PreSaveAction function that I am trying to get a people picker field value and use it in an IF statement. I want to set the AssignedTo only if it is blank. If the person is not validated by pressing the “Check Names” icon prior to saving, the value returned is blank instead of having the value typed by the user and displayed on the screen. I saw a post dated Oct 8, 2010 that had a similar issue. Your reply spoke about a “blur” event when focus is taken away from the people picker. I would appreciate an example of this. Here is my script (Currently using MOSS 2007):

    function PreSaveAction() {
    var fields = init_fields_v2();
    var strAssignedTo = getFieldValue(“AssignedTo”);
    alert(“strAssignedTo: ” + strAssignedTo);
    var strAssignedGroup = getFieldValue(“AssignedGroup”);
    if (strAssignedTo == “”) {
    var strAssignedToUpdate = “c200Feedback” + strAssignedGroup.replace(/[^A-Za-z0-9]/g, “”);
    setFieldValue(“AssignedTo”, strAssignedToUpdate);
    }
    return false; // set to false for testing
    }

    Thanks for any help you can provide!

    1. Hi,
      Use something like this to add a blur function:

      // Auto resolve picker on blur
      setAutoResolve("FieldInternalName");
      
      function setAutoResolve(fin){
      	var toFind = "div.ms-inputuserfield";
      	if(!browseris.ie5up && typeof(_fV4UI)==='undefined'){
      		toFind = "textarea";
      	}	
      	$(fields[fin]).find(toFind).bind('blur',function(){
      		$(this).parents("td.ms-formbody:first").find("img:first").trigger("click");
      	});
      }
      

      Change “FieldInternalName” to your fields internal name.

      Alexander

  63. Thanks Alexander. Unfortunately, it is not working for me yet. I will keep trying tomorrow, but any tips you may have will be helpful. (I did change the “FieldInternalName” to the appropriate value…)

    1. Hi,

      Still no luck. I am calling the function with: setAutoResolve(“AssignedTo”);
      I put in a couple alerts to see what was happening. I get alert 1 & 4, but not 2 or 3.
      alert(“1”);
      $(fields[fin]).find(toFind).bind(‘blur’,function(){
      alert(“2”);
      $(this).parents(“td.ms-formbody:first”).find(“img:first”).trigger(“click”);
      alert(“3”);
      });
      alert(“4”);
      Any ideas of what I am doing wrong?
      Thanks!
      Carolyn

  64. Hi Alexander,

    i tried to set a DueDate with time: setFieldValue(‘DueDate’,[’05/28/2012′,’09 AM’,’45’]);
    but I got this “05/28/2012 00 45” in my form and not “05/28/2012 09 45” as I had expected.

    Where is the problem?
    Rolf H.

  65. I really was browsing for techniques for my web site
    and came across your posting, “Get or Set value for SharePoint field in NewForm, EditForm
    and DispForm (Get only in DispForm) « SharePoint JavaScripts”,
    will you care in cases where I personally work with a
    number of of your concepts? I am grateful -Shanna

  66. Hello Alexander,

    We want to use this code for a mulitlookup field and used following which does not work:

    fields = init_fields_v2();
    var myMultiLookup = getFieldValue(‘MultiLookup’);
    alert(myMultiLookup);

    other fields work OK.

    Please advise.
    Kind regards,
    Mario

  67. Hi Alexander,
    I’ve added ‘spFIeldTarget’ as a case but the field is a bit more complex than a simple multiline text or something. How do you go about getting the details needed to properly added a field type? This is a sharepoint 2007 Audience Target field which I need to set the value of. There seems to be a bug with the field in that even if set to Required, SharePoint lets the form be submitted anyway. Oi!

  68. I need to assign multi select check box field value to single line text field.

    Here is my code

    fields = init_fields_v2();

    // Get value from a multicheck field(multi selection check box value)
    var myRichTextValue = getFieldValue(‘Multicheck’);

    // set the value to assignfield(single line text field)
    setFieldValue(‘assignfield’,’myRichTextValue’);

    I tried the code but the value is not set

    Need help on this!

    1. Hi,
      You should not have quotes around the variable “myRichTextValue”, the code should look like this:

      var myRichTextValue = getFieldValue("Multicheck");
      setFieldValue("assignfield",myRichTextValue);

      Please note that the field names “Multicheck” and “assignfield” must be addressed by their FieldInternalName.

      Alexander

  69. Alex,

    I couldn’t get the SPFieldChoice to work with SP2010 / Jquery 1.7.1 & I noticed that SPFieldChoice for dropdown is setting using .attr – 1.6+ uses .prop

    I changed it to:
    thisField.find(‘select option’).each(function(){
    if($(this).text()==newVal){
    $(this).attr(‘selected’,’selected’);
    }else{
    $(this).removeAttr(‘selected’);
    }
    });

    And it works like a charm.

  70. Hi Alex,
    I want to set people picker value to null when form loads. currently it is getting autopopulated. What i need to do to avoid this autopopulation??

  71. Thanks for this useful post. It is excellent. 🙂
    Please let me know how to get value of ‘SPFieldTargetTo’ type. Appreciate your help.

    Thanks,
    Osmita

  72. Hi Alex,

    Firstly, this is a fantastic tool…

    Just one thing to note. I had to add an ‘else’ statement onto the SPFieldMultiChoice to clear the attrebute for ‘checked’ if the value was noe one that was passed in to be checked in the ‘setFieldValue’ as I was calling the function many times and each time it had different values to populate the SPFieldMultiChoice with and without this else option to remove the attribute of checked if the specific option was not needed the field was showing some items as checked that were not needed to be checked. I thought I would mention it as it may be a nice little addition as a fail-safe in the future… And I hope this makes sense…

    Cheers,
    Luke

  73. Hi Alexander,

    Thanks for the article. it helped me while i was working on SharePoint 2010. currently I am working on SP 2013 and not able to put the validation for people picker and multiline text box. could you please guide me through this.

    Thanks
    Yogendra

  74. Not working with custom NewForms
    Reason being that those do not expose the FieldInternalName string etc.
    Workaround is to use SPDesigner and go to: All Files/Lists/.
    Then copy the original NewForm.aspx file and rename it to whatever you want.

    This however kills the ability to customize the NewForm, but most of the time, such customizations is to simply hide certain fields.
    Why not add a ‘hideField’ function to your script, that would make it even more awesome.

    Forexample something in the area of (just a quick mockup):
    function hideField(fin,newVal,onLoad){
    if(typeof(onLoad)===’undefined’){
    onLoad = true;
    }
    // If not already done – init all fields
    if(typeof(fields)===’undefined’){
    fields = init_fields_v2();
    }
    // Return if FieldInternalName is not found
    if(fields[fin]===undefined){
    return;
    }

    var thisField = $(fields[fin]);
    if(thisField){
    thisField.style.display=’none’;
    }

    }

    1. Hi,
      This is an old post, but if you use the latest spjs-utility.js and a newer version of jQuery, this should work in IE 10. What exactly are you trying to do?

      – and please note that this code is for a unmodified form.

      Alexander

  75. Hi Alex, I have had a working version of this script. I made some updates with your updated version and now I am having an issue getting a field value from a multipleselect choice field. This is sp 2010, and am using jquery 1.6.4 spjs ver 1.7.9. and on the presave function

    function PreSaveItem(){	
    var my_ID = getFieldValue('_ID');
    //var yearVal = getFieldValue('Year',false);
    //alert(yearVal);
    //setFieldValue('YearValue',yearVal);
    
    	var listGuid, listBaseUrl, query, res;
    	listGuid = _spPageContextInfo.pageListId;
    	listBaseUrl = _spPageContextInfo.siteServerRelativeUrl !== "/" ? _spPageContextInfo.siteServerRelativeUrl : "";	
    	query = "";
    	res = spjs_QueryItems({"listName":listGuid,"listBaseUrl":listBaseUrl,"query":query,"viewFields":["ID"],"rowLimit":"1","scope":"Recursive"});
    	if ( my_ID == "") {	
    		if(res.count === 0){
    			$("input[title='_ID']").val("1");
    		}else{
    			$("input[title='_ID']").val(parseInt(res.items[0].ID,10)+1);
    		}
    	}
    	else {
    	$("input[title='_ID']").val(GetUrlKeyValue("ID"));
    	}	
    	return true;
    }
    

    I have commented out where the issue is. I can get the value of _ID, but when I try the multiple select It errors, or wont save. am I missing something.
    source FIN = Year
    Target FIN = YearValue

  76. Hi there, I have a requirement as follows.
    I have a Hyperlink field in which I have to set blank value in the URL and some description in the description part in the new form. Iam able to auto-populate any value in the URL field, but the description part is taking the same value then.

    While in edit form I need to get the url value put by the user for a validation to check if the full url contains the required path or not.

    Kindly help here please.
    Please note I am using SP 2007 and dont have access to designer. I have to do it through scripting only.

    1. Hi,
      Include a reference to spjs-utility.js and then use this code:

      var fields = init_fields_v2();
      var urlField  = $(fields["TheFieldInternalNameOfYourHyperlinkField"]).find("input:first");
      var urlDescriptionField  = $(fields["TheFieldInternalNameOfYourHyperlinkField"]).find("input:last");
      
      // Set value
      $(urlDescriptionField).val("my desctiption"); 
      // alert value
      alert($(urlDescriptionField).val());

      Hope this helps.
      Alexander

  77. How to Hide /Show div on sharepoint check box selection using javascript/ecmascript?

    In the scenario div contains some other controls i need to show the div when the user checked the check box in sharepoint list form

    Suggest me on this ?

    1. Hi,
      Use this code below the form in newform or edirform:

      <div id="myDiv" style="display:none;">here is the text to show when the user clicks the checkbox</div>
      
      <script type="text/javascript" src="/Scripts/jquery.min.js"></script>
      <script type="text/javascript" src="/Scripts/spjs-utility.js"></script>
      <script type="text/javascript">
      
      var fields = init_fields_v2();
      
      // Page load
      showMyDiv();
      function showMyDiv(){
      	var bVal = getFieldValue("MyBool");
      	if(bVal){
      		$("#myDiv").show();
      	}else{
      		$("#myDiv").hide();
      	}
      }
      // Click
      $(fields["MyBool"]).find("input:checkbox").bind("click",function(){
      	showMyDiv();
      });
      </script>
  78. Hi Alexander,
    I’m trying to set a Managed Metadata field named “Property” using the following code:

    fields = init_fields_v2();
    setFieldValue(‘Property’,’Ora’);

    but it is yielding no results. I will eventually be trying to use a variable in the place of ‘Ora’, but I can’t even fill the field at all. Can you shed any light on the matter?

    Thanks,
    Avery

      1. <!–

        fields = init_fields_v2();
        setFieldValue(‘Property’,’Ora’);

        –>

  79. Here’s the code without any … hopefully that will show

    script type=”text/javascript” src=”/sites/ecm/site assets/jquery-1.11.1.min.js”/script
    script type=”text/javascript” src=”/sites/ecm/site assets/spjs-utility.js”/script
    script type=”text/javascript”
    fields = init_fields_v2();
    setFieldValue(‘Property’,’Ora’);
    /script

  80. Hi How can i update the choice fields in sharepoint list in office 365 through Client object model . i can able to update the title,Description column.But i m using the same way for choice fields i could’t . Can u plz help me !!

  81. function MainFunction() {

    objContext = new SP.ClientContext.get_current();
    objWeb = objContext.get_web();
    objList = objWeb.get_lists().getByTitle(“CAB Participant Tasks”);
    objContext.load(objList);
    JSRequest.EnsureSetup();
    var SelectedItemID = JSRequest.QueryString[“ID”]; // get the selected list item ID
    alert(SelectedItemID);

    this.oListItem = objList.getItemById(SelectedItemID);

    // oListItem.set_item(‘Title’, ‘Suma’);

    //Review the CAB Presentation Deck Template
    var chkCABPresentationDeck =document.getElementById(‘chk_Review_CAB_Training’).checked;
    if(chkCABPresentationDeck=true)
    {
    // this.oListItem = objList.getItemById(SelectedItemID);
    alert(chkCABPresentationDeck);
    // oListItem.set_item(‘ChoiceColumn’, ‘ChoiceValue’);
    // listItem.set_item(‘DateColumn’,currDate);
    oListItem.set_item(‘Review the CAB Presentation Deck Template’, 1);
    oListItem.update();

    }

    1. Hi,
      I suspect you must use the internalname of the field – “Review the CAB Presentation Deck Template” is the display name.

      Find the FieldInternalName by searching for the display name in the Display form of the list “CAB Participant Tasks”.

      Alexander

    1. Unable to get value of the property ‘focusValidOnThisNode’: object is null or undefined .have included the below ref scripts file s.
      Sp,Core,Runtime.js files and also added init.js … if anything else i need to add ?

  82. Hi ,
    plz look on to the below code . i used internal name also . But i cant able to update . For choice fields we can use 1 or 0 ? ‘Yes ‘ or ‘No’.

    var chkMentor=document.getElementById(‘chk_CAB_Mentor’).checked;
    if(chkMentor=true)
    {

    alert(chkMentor);

    oListItem.set_item(‘FieldName%5FC7B61645%5FC206%5F4D3C%5F85E’, 1);

    oListItem.update();
    alert(‘Sucess’);

    }

    objContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFail));

  83. Hello! I’ve got SharePoint 2010. Am I doing smth wrong? Nothing happens…(

    fields = init_fields_v2();
    setFieldValue(‘Title’,’test’);

      1. Thanx for the answer!
        Dev Tools Console:
        HTML1202: http://sp2010/requests/Lists/UnderloadingOrders/NewForm.aspx?RootFolder= is running in Compatibility View because ‘Display intranet sites in Compatibility View’ is checked.
        NewForm.aspx
        SEC7115: :visited and :link styles can only differ by color. Some styles were not applied to :visited.
        NewForm.aspx
        HTML1114: Codepage unicode from (UNICODE byte order mark) overrides conflicting codepage windows-1251 from (12)
        NewForm.aspx
        HTML1114: Codepage unicode from (UNICODE byte order mark) overrides conflicting codepage windows-1251 from (12)
        NewForm.aspx

      2. Oh ,man sorry for disturbing, the reason was that my CEWP was added before the list webpart. Really, i may have read the manual inattentivaly:(

  84. Hi Alex,
    your last reply on my query helped me immensly.Thanks for that and now I have another issuw bugging me. 🙂

    I have used getFieldValue() function to get the value of a multiline of text field. However iam getting the value as below.

    textwreiiten. Please let me know how to get it fixed.

  85. Hi Alexander,

    I’ve had a lot of success with your spjs-utility.js code, with the only exception being SPFieldLookupMulti field type.
    I have 2 multi valued lookup fields on a list – MLkup1 and MLkup2.

    MLkup1 has 2 values – “Argentina” and “Australia.”
    I have a CEWP on my edit form with the following code:

    $(document).ready(function(){
    var mult = getFieldValue(“MLkup1”);
    alert(mult);
    setFieldValue(“MLkup2″, mult)
    });

    The alert in my code above returns “Argentina,Australia.”
    I’ve even put an alert in spjs-utility.js…
    alert(thisField.find(‘input:hidden[id$=”Picker_initial”]’).val());
    … which returns
    “2|tArgentina|t4|tAustralia”

    I’m probably doing something stupid. Any help would be most appreciated.

    1. If your mission is to replicate the selections in “MLkup2” you might have to add a delay to ensure the lookup column has rendered completely before trying to set it. Try wrapping the code like this:

      $(document).ready(function(){
      setTimeout(function(){
        var mult = getFieldValue(“MLkup1″);
        alert(mult);
        setFieldValue(“MLkup2″, mult);
      },1000);
      });

      PS: I assume the lookup column are targetting the same list so that the options are valid choices.

      Alexander

  86. Yes, I am using version 1.206 (Feb 24, 2015). And the lookup columns are targeting the same list. I added the delay as you suggested, but still no luck. I should have probably stated earlier that I’m in SharePoint 2007 environment.

    1. Hi,
      The reason is that the “setFieldValue” function must have an extra attribute “onload”, as the MultiLookup control must be set differently if it has not finished rendering – try this:

      setFieldValue("TheNameOfYourLookupMulti","aaa,bbb",false);

      Alexander

  87. In SP2013 html generation is changed, I was disabling making readonly to rich text editor using following script in sp2010
    $(document).ready(function(){
    var tags = document.getElementsByTagName(“div”);
    var index=0;
    var divID=””;
    for (var i=0;i -1){
    index = i;
    }
    }
    }//end for loop
    //Removing _label from id to get inner div’s id
    var txtfieldid = tags[index].id.substr(0,tags[index].id.length-6);
    //disabling editing feature
    $(“div#”+txtfieldid+””).attr(‘disabled’,’disabled’);
    $(“div#”+txtfieldid+””).attr(‘contentEditable’, ‘disable’);
    Now this is not working because it wraps in span

    Not sure how to do in new scenario

  88. you can try using something like this to hide the original td and add a new one with only the text contents.

    var fields = init_fields_v2(); 
    var fieldVal = getFieldValue("yourFieldInternalName");
    $(fields["yourFieldInternalName"]).find("td.ms-formbody").hide().after("<td class='ms-formbody'>"+fieldVal+"</td>");

    Alexander

  89. Alexander,

    Looking to copy the value out of a vLookup field that points into an Enhanced Rich Text field into a multiline (ERT) field using a button. It looks like the vLookup isn’t passing anything into the getFieldValue function. Is there a way to make this happen using this solution in DFFS?

  90. Currently there is no built in method to pull this from a vLookup column, but you can use a few lines of custom code like this:

    function custom_get_vLookupValue(tr,td){
    	var vLookupTable = $("#vLookup_vLookupTasks_"+GetUrlKeyValue("ID")+" table.vLookupTable");
    	if(vLookupTable.length > 0){
    		return $(vLookupTable).find("tr.vLookupTableRow:eq("+(tr-1)+")").find("td.childTable:eq("+td+")").html();
    	}
    }
    
    /* How to use */
    function test_get_vLookupValue(){
    	var vLookupValue = custom_get_vLookupValue(2,2);
    	alert(vLookupValue);
    }

    Change “vLookupTasks” with the name of your vLookup field, and adjust the tr and td values to match the row number and cell you want to retrieve.

    Please not that this code will only work if the vLookup table has been drawn (must be visible in a tab).

    Alexander

    1. Once again, you deliver!

      I ended up combining the above code with the setFieldValue- works beautifully. We have 4 vLookups so I’ve altered the code for each. There’s probably room to condense the code. Here’s an example of what we’ve done.

      //vLookupGeneral
      function custom_get_vLookupGenValue(tr,td){
      var vLookupTable = $(“#vLookup_vLookupGen_”+GetUrlKeyValue(“ID”)+” table.vLookupTable”);
      if(vLookupTable.length > 0){
      return $(vLookupTable).find(“tr.vLookupTableRow:eq(“+(tr-1)+”)”).find(“td.childTable:eq(“+td+”)”).html();
      }
      }

      function get_vLookupGenValue(){
      var vLookupValue = custom_get_vLookupGenValue(1,1);
      setFieldValue(‘General’, vLookupValue);
      }

      //vLookupID
      function custom_get_vLookupIDValue(tr,td){
      var vLookupTable = $(“#vLookup_vLookupID_”+GetUrlKeyValue(“ID”)+” table.vLookupTable”);
      if(vLookupTable.length > 0){
      return $(vLookupTable).find(“tr.vLookupTableRow:eq(“+(tr-1)+”)”).find(“td.childTable:eq(“+td+”)”).html();
      }
      }

      And then created a header with a button under each field:

      <input type=”button” value= “Copy to Action Items” onclick= “get_vLookupGenValue();return false;”>

  91. I’m tring to use script, but nothing works..
    here my code

    fields = init_fields_v2();

    setFieldValue(‘Code_x0020_Gmao’,’test’);
    setFieldValue(‘Code_x0020_drop’,’1′);

    alert(“test”)

    Code_x0020_Gmao is a text line
    Code_x0020_drop is a lookup value , 1 is the ID of desiderated value.

    Script is loaded, alert work , the same for alert :
    alert(typeof(setFieldValue));

    Can you help me?

  92. Which version of SharePoint are you using? – if it is SP2013 you might have to delay the execution of the code – try wrapping it like this:

    SP.SOD.executeOrDelayUntilEventNotified(function () {
    		    setFieldValue("Code_x0020_Gmao","test");
    		   setFieldValue("Code_x0020_drop","1");
    
    		   alert(“test”)
    		}, "sp.bodyloaded");

    Alexander

  93. Now my script is this :

    setTimeout(function(){
    fields = init_fields_v2();

    setFieldValue(“Intervenant_x0020_Alpa_x002f_EE”,”ALPA”);

    alert(“test1”)
    },500);

    alert(“test2”)

    I receive alert test2 and then test1, that meaning that scipt don’t go in error ??

    May be the value that i want put in lookup zone is not good ? in my lookup dropdown i find “ALPA” (ID.1) , is correct use value or ID?

    Thanks

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.