Get field value for all SharePoint FieldTypes or set field as read only in EditForm

16.10.2010 The function getFieldValue is posted in another – more updated – version here.

29.04.2010 Updated the code for the file “GetFieldValueOrSetAsReadonly.js” to support “SPFieldUserMulti” and for getting the field value in DispForm.


I have had several requests for a solution for setting fields as read only in EditForm. I have created this script to achieve this.

This script enables you to get the field value for any SharePoint field type in EditForm, and to set the field as read only by grabbing it’s value, hiding the <TD>, and adding a clean <TD> with the value in it’s place.

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 use another version, please update the reference in the code.

Read here how to add a CEWP to EditForm, and how to get the FieldInternalNames for your fields.

Add this code to a CEWP below the EditForm:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/GetFieldValueOrSetAsReadonly.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
// Array of FieldInternalNames to make readonly
var arrToMakeReadOnly = ['Title','MySelect','MyPeoplePicker','Lookup','Bool','Hyperlink','DateTime','Multiline'];

// The function call must be wrapped in the &quot;$(document).ready&quot; to work with complex field types
$(document).ready(function(){
	readOnlyFieldArray(arrToMakeReadOnly);
});
&lt;/script&gt;

The above code sets all fields in the array “arrToMakeReadOnly” as readonly. To simply get a fields value, do it like this:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/GetFieldValueOrSetAsReadonly.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

// The function call must be wrapped in the &quot;$(document).ready&quot; to work with complex field types
$(document).ready(function(){
	var myValue = getFieldValue(&quot;Insert the FieldInternalName of your field here&quot;);
});
&lt;/script&gt;

To get a fields value in DispForm, do it like this:

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/GetFieldValueOrSetAsReadonly.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

	var myValue = getFieldValue(&quot;Insert the FieldInternalName of your field here&quot;,&quot;disp&quot;);

&lt;/script&gt;

The sourcecode for the file “GetFieldValueOrSetAsReadonly.js”:

/* Get field value for all field types, or set as readonly in EditForm 
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * v1.1
 * LastMod: 29.04.2010
 * LastChange: Supporting &quot;SPFieldUserMulti&quot; and for getting the field value in DispForm
 * ---------------------------------------------
 * Include reference to jquery - http://jquery.com
 * ---------------------------------------------
 * Call from a CEWP below the list form in EditForm like this:
	&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
	&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/readOnlyForSharepointFields.js&quot;&gt;&lt;/script&gt;
	&lt;script type=&quot;text/javascript&quot;&gt;
	// Array of FieldInternalNames to make readonly
	var arrToMakeReadOnly = ['Title','MySelect','MyPeoplePicker','Lookup','Bool','Hyperlink','DateTime','Multiline'];
	
	// The function call must be wrapped in the &quot;$(document).ready&quot; to work with complex field types
	$(document).ready(function(){
		redOnlyField(arrToMakeReadOnly);
	});
	&lt;/script&gt;
*/

function readOnlyFieldArray(arrayOfFieldInternalNames){
	$.each(arrayOfFieldInternalNames,function(i,fin){
		var fieldValue = getFieldValue(fin);
		if(!fieldValue)return false;
		thisField=$(fields[fin]);
		// Strip off any &quot;formvalidation star&quot;		
		thisField.find('.ms-formlabel span.ms-formvalidation').remove();
		// Set as &quot;readOnly&quot;
		thisField.find('td.ms-formbody').hide().after(&quot;&lt;td class='ms-formbody' style='width:450px'&gt;&quot;+fieldValue+&quot;&lt;/td&gt;&quot;);
	});
}

function getFieldValue(fin,edit_OR_disp){
// If not already done - init all fields
if(typeof(fields)=='undefined')fields = init_fields();
// Return if FieldInternalName is not found
if(fields[fin]==undefined)return;
var thisField = $(fields[fin]);
// If &quot;edit_OR_disp&quot; is undefined, default to &quot;edit&quot;
if(edit_OR_disp==undefined)edit_OR_disp='edit';
	if(edit_OR_disp=='disp'){ // If &quot;disp&quot;
		var valRaw = $(fields[fin]).find('.ms-formbody').text();
		return (valRaw.replace(/[ xA0]+$/,'')=='')?'':valRaw.replace(/[ xA0]+$/,'');
	}else{ // If &quot;edit&quot;		
		var fieldType = $(fields[fin]).attr('FieldType');
		if(fieldType==undefined){
			alert(&quot;The attribute &quot;FieldType&quot; is missing.nEnsure the function init_fields() used is the one included in the file &quot;GetFieldValueOrSetAsReadonly.js&quot;.&quot;);
			return false;
		}
		returnVal = '';		
		switch(fieldType){
			case 'SPFieldText':
			case 'SPFieldNumber':
			case 'SPFieldCurrency':
				returnVal = thisField.find('input').val();
			break;
			case 'SPFieldChoice':
				if(thisField.find('input:radio').length&gt;0){
					returnVal = thisField.find('input:radio:checked').next().text();
				}else{
					returnVal = thisField.find('select').val();
				}
			break;
			case 'SPFieldMultiChoice':
				var multiChoice = [];
				thisField.find('input:checkbox:checked').each(function(i,opt){
					opt = $(opt);
					multiChoice.push(opt.next().text());
				});
				returnVal = multiChoice.join('&lt;br /&gt;');
			break;
			case 'SPFieldUser':
				var myPeoplePicker = thisField.find(&quot;div[id='divEntityData']&quot;);
				returnVal = myPeoplePicker.attr('displaytext');
				returnVal = (returnVal!=undefined)?returnVal:'';
			break;
			case 'SPFieldUserMulti':
				var userMulti = [];
				thisField.find(&quot;div[id='divEntityData']&quot;).each(function(i,div){
					thisVal = $(div).attr('displaytext');
					if(thisVal!=undefined){
						userMulti.push(thisVal);
					}				
				});
				returnVal = userMulti.join('&lt;br /&gt;');
			break;
			case 'SPFieldLookup':
				if(thisField.find('select').length&gt;0){
					returnVal = thisField.find('select option:selected').text();
				}else{
					returnVal = thisField.find('input').val();
				}
			break;
			case 'SPFieldLookupMulti':
				var lookupMulti = [];
				thisField.find(&quot;select:last option&quot;).each(function(i,opt){
					opt = $(opt);
					lookupMulti.push(opt.text());
				});
				returnVal = lookupMulti.join('&lt;br /&gt;');
			break;
			case 'SPFieldBoolean':			
				returnVal = (thisField.find('input').attr('checked')==true)?true:false;
			break;
			case 'SPFieldURL':
				var link = thisField.find('input:first').val();
				var descr = thisField.find('input:last').val();
				returnVal = &quot;&lt;a href='&quot;+link+&quot;'&gt;&quot;+descr+&quot;&lt;/a&gt;&quot;;
			break;
			case 'SPFieldDateTime':
				var date = thisField.find('input:first').val();
				var hour = thisField.find('select:first option:selected').val()
					hour = (hour==null)?'':hour.match(/^[d]+/)+&quot;:&quot;;
				var AMPM = thisField.find('select:first option:selected').val()
					AMPM = (AMPM==null)?'':AMPM.match(/AM|PM/);
				var minutes = thisField.find('select:last option:selected').val();
					minutes = (minutes==null)?'':minutes;
				returnVal = date+&quot; &quot;+hour+minutes+&quot; &quot;+AMPM;
			break;
			case 'SPFieldNote':
				returnVal = thisField.find('textarea:first').val();
			break;
			case 'customHeading':
				returnVal = '';
			break;
			default:			
			returnVal = &quot;Unknown fieldType: &lt;strong&gt;&quot;+fieldType+&quot;&lt;/strong&gt;, please check the script.&quot;;
		}
		if(returnVal==='')returnVal=&quot;&amp;nbsp;&quot;;
		return returnVal;
	}		
}

function init_fields(){
	var res = {};
	$(&quot;td.ms-formbody&quot;).each(function(){
	var myMatch = $(this).html().match(/FieldName=&quot;(.+)&quot;s+FieldInternalName=&quot;(.+)&quot;s+FieldType=&quot;(.+)&quot;s+/);	
		if(myMatch!=null){
			// Display name
			var disp = myMatch[1];
			// FieldInternalName
			var fin = myMatch[2];
			// FieldType
			var type = myMatch[3];
			if(type=='SPFieldNote'){
				if($(this).find('script').length&gt;0){
					type=type+&quot;_HTML&quot;;
				}
			}
			if(type=='SPFieldLookup'){
				if($(this).find('input').length&gt;0){
					type=type+&quot;_Input&quot;;
				}
			}
			// Build object
			res[fin] = this.parentNode;
			$(res[fin]).attr('FieldDispName',disp);
			$(res[fin]).attr('FieldType',type);
		}		
	});
	return res;
}

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

Note!
The function init_fields() used in this code is the new one posted here: Revised function init_fields()

It has additional functionality not found in previous versions. Be sure to update the function if adding this to existing code.

Ask if anything is unclear

Regards
Alexander

72 thoughts on “Get field value for all SharePoint FieldTypes or set field as read only in EditForm”

  1. Hi – How can this field be set as Read only to specific sharepoint group and editable by another SharePoint Group.

    Thanks in Advance
    Siby

    1. The article has examples of CEWP-code to implement the solution in the top three code blocks.

      What exactly is the problem?

      Alexander

  2. I was trying to open outlook with a button from the dispform.aspx page and attach the dispform.aspx field values in the subject and body of outlook. In the subject field I will have the title and id of the list item data fetched. In the body, I will have the rest of the data pasted or copied. How do I accomplish this? I added the cewp as you listed. I place a button and called the function but no result. How do I accomplish this? Please help! Thank you!

  3. Alexander, here is an example how I placed the code in CEWP.

    function id2() {
    var myValue = getFieldValue(“Title”,”disp”);
    retrun myValue;
    }

  4. here is a simple one. I was just trying to get the Title from the disform.aspx but nothing is retrned. check this out.

    function id2() {

    var myValue = getFieldValue(“Title”,”disp”);
    //var myValue = 10;

    window.alert(myValue);

    }

  5. I am sorry. here is the full code

    function id2() {
    var myValue = getFieldValue(“Title”,”disp”);
    window.alert(myValue);
    }

  6. I was getting “undefined”. It is working now. The problem is when I hide the the dispform.aspx page, it returns empty. If i don’t hide the dispform.aspx page, it returns the values perfectly. I don’t know why? I was trying to do, customize the dispForm.aspx page and hide it. Then place a button on the new customized dispaspx page. Onclick event, I called my function from the hidden CEWP. Because i hid the original dispform.aspx page, it returns nothing. what is the problem? Please help. Thank you!

  7. Hi Alexander,

    I would like to set the field “Title” as readonly only if my column status = Approved.
    Do I have to put:
    var myValue = getFieldValue(“Status”);
    var arrToMakeReadOnly = [‘Title’]
    If myValue = “Approved”
    {
    redOnlyFieldArray(arrToMakeReadOnly);

    }
    Could you please help me to to this?
    It would be great!

    Thanks.

    1. Hi,
      Try this:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/GetFieldValueOrSetAsReadonly.js"></script>
      <script type="text/javascript">
      // The function call must be wrapped in the "$(document).ready" to work with complex field types
      $(document).ready(function(){
      	var status = getFieldValue('Status');
      	if(status=='Approved'){
      		redOnlyFieldArray(['Title']);
      	}
      });
      </script>
      

      Alexander

  8. Hello Alex,

    Thank you for your prompt response. This solution works for some of my fields and not for others. It works for ‘CTO’ but not for SID, it actually skips SID and affects LName… Why do you think that is?

    Regards,
    M

  9. Hi Chris,

    Is it possible to set a choice field as readonly. Let me explain.
    I have a choice field status wich can take 3 values. (Approved, rejected, To complete). Is it possible to set the choice “To complete” as readonly.

    Status: Approved
    rejected
    To complete

    Thanks for your response.

    1. Hi,
      Put this code in a CEWP below the form:
      Replace the FieldInternalName “Status” with your own FieldInternalName.

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      // Radio button
      $(fields['Status']).find('input:radio').each(function(){
      	if($(this).next().text()=='To complete'){
      		$(this).next().andSelf().attr('disabled','disabled');
      	}
      });
      
      // Dropdown select
      $(fields['Status']).find('option').each(function(){
      	if($(this).val()=='To complete'){
      		$(this).attr('disabled','disabled');
      	}
      });
      
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}
      	});
      	return res;
      }
      </script>
      

      Alexander

  10. Hi,

    it works well but on a Datetime field, there is write ‘null’ after the date. maybe because the hours are not fill, is there a way to delete it?

    And how its works with a businessdata field ?
    thanks

    1. Hi,
      Look at the top of the article – there you find a link to a newer version.

      Try it out and see if it handles the date and time field differently.

      Alexander

  11. Hi,

    your solution seems to be quite cool – thanks for sharing the code.
    Do you have an extenstion for hiding TaxonomyFields in SharePoint 2010, too?

    Thanks,
    Fidy

  12. Using the “arrtomakereadonly” this works fine in my test area but in the production area that is also running your ToolTips script in a CEWP i get the following error …….The attribute “Field Type” is missing. Ensure the function init_field() used is the one included in the file “GetFieldValueOrSetAsReadOnly.js”
    Any Ideas?

    1. Sorry, missed your not in RED explaining this……how can i get my tool tips back on the fields that I just made readonly on the edit form?

  13. Hey A,

    Does this sript have a limitation to the number of fields or for the number field type / date field type?

    I have a bunch of fields, when I set the fields to readonly most of the fields convert. All except the number fields. I do have close to 50 fields I am setting to read only and the last few fields which are number and date fields do not change to read only.

    Any thoughts?

    1. Hi,
      No limit. Check your FieldInternalNames (the first one not working).

      It may be a problem with the code, but please test the fieldTypes with a “fresh array” containing only those types not working.

      Alexander

  14. Alex, Thank you for sharing.

    Just wondering if anyone has tried to set readonly on a “Multiple lines of text” field with “Append Changes to Existing Text” set to yes.

    The field is hidden but I don’t see the appended text

  15. Thanks this worked for me.

    Is there any way to set feild as mandatory from javascript? I have to show hide field based on task and in certain task I have to set the fields as mandatory. I cannot do it from SharePoint as it expects the mandatory values to be there even when they are hidden.

    Cheers

    1. Thanks for the quick response!

      However, I’ve put the updated version of init_fields() and still doesn’t work.

      Is there a workaround??

      Would be very grateful if there is one..:)

    2. Hi,
      Do you have multiple instances of the function in the page? – it has been used in many of my solutions.

      If not, which version of Firefox do you use?

      Alexander

    3. Alexander,

      By putting an alert in init_fields() it seems it runs only once.

      I’ve tested in Firefox 5.0.1 and 3.6.2

      Many thanks again for the help!

    4. Hi,
      This is strange. I have used this in Firefox for a long time and only recently (after v5 i think) needed to update the function init_fields.

      Is the form you are using a standard SharePoint form, or has it been modified in SharePoint Designer?

      Alexander

    1. If in SP2007, yes, but even better (and a must in SP2010) is to use the content link property. You then put the file in a document library or a folder created in SharePoint Designer and link to it in the “Content link” field of the CEWP

      Alexander

    2. Thanks for the help,Alexander but as it seems I can’t make it work..

      I’ve put the code in a js file in a folder I created in SPD and linked it through Content link property of the CEWP.

      But again in IE its ok in Firefox it doesn’t work..

    3. Which operating system do you use for Firefox?

      Try to step trough the init_fields function and see if you can find anything. Try alerting “type” and see if it gets it at all.

      Alexander

  16. Hi, when using your code to hide a rich text field it does not make it readonly but display message: “Unknown fieldType: SPFieldNote_HTML, please check the script.” I like to know if you can show me how to make a rich text field read only.

  17. Trying this method currently on a lookup 20+ items, getting “Unknown fieldType: SPFieldLookup_Input, please check the script.” any advice?

      1. Alexander,
        Thank you for the prompt response. Being a complete noob, I really did review the updated version pages and comments. but i posted on the older page.

        I am still unclear how to apply readonly with either function getfieldvalie or setfieldvalie. I was using this:

        $(document).ready(function(){
        readOnlyFieldArray(arrToMakeReadOnly);
        }

        until the a field in my array changed from under 20 to 20+ and became a complex lookup field.

        Could you please provide me with a basic example of the script to set a complex lookup field as readlonly with the updated functions? (or direct me to where I may have overlooked it.)

    1. Hi,
      Sorry for the late reply.

      Get the latest version of spjs-utility.js here. Use this code in a CEWP in the form (below the form web part) where you want to set the field as read only:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/spjs_utility - blog/spjs-utility.js"></script>
      <script type="text/javascript">
      var fields = init_fields_v2();
      
      doReadOnly(['MyLookupField']);
      
      function doReadOnly(array){
      	var fieldValue, thisField;	
      	$.each(array,function(i,fin){			
      		thisField = $(fields[fin]);
      		fieldValue = getFieldValue(fin);
      		thisField.find('td.ms-formbody').hide().after("<td class='ms-formbody' style='width:450px'>"+fieldValue+"&nbsp;</td>");
      	});
      }
      
      </script>
      

      Alexander

      1. Thank you Alexander,

        I actually got this to function based on your comments to Maureen (below) and failed to update my inquiry. I removed the declaration for GetFieldValueOrSetAsReadOnly.js, and then simply pulled the readOnlyFieldArray function fromm there into my script. Didnt realize at the time there was a duplication of the older GetFieldValue function causing the issue. Works perfectly! Thanks a million!

  18. This works great except for a lookup field that has values with spaces (i.e Mobility Support, Mobility Development, etc.) then when I try to disable the field that contains one of those values iget the message “Unknown fielType: SPFieldLookup_Input, please checkthe script. lookup fields that have values that do not contain spaces work fine. I am trying to use this in a demo I am giving tomorrow (Monday 2/13) so if you are on line and can help me with a solution I would greatly appreciate it. By the way, great documentation and easy to follow.

  19. I am sorry, I am new to all of this and am not understanding. Rieght now in my CEWP I have this code:

    // Array of FieldInternalNames to make readonly
    //Using Internal field names for Activity and Team Member
    var arrToMakeReadOnly = [‘Acitvity’,’WorkItem’,’_x0074_m2′];
    // The function call must be wrapped in the “$(document).ready” to work with complex field types
    $(document).ready(function(){
    readOnlyFieldArray(arrToMakeReadOnly);
    });

    when I go and look at the updated code am I just supposed to include it in this code or replace this code altogether with below:

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

  20. OK that did not work so I am not understanding….I feel stupid and hate bothering you but do nto understand what is going on. now even one lookup that was getting disabled is not.. I am sorry to be a bother but need to understand

    1. In the file spjs-utility.js you find an updated version of the function “getFieldValue”. You could either get the updated version and put it in the file “GetFieldValueOrSetAsReadOnly.js”, or move the function “readOnlyFieldArray” into your CEWP and refer “spjs-utility.js” in stead of “GetFieldValueOrSetAsReadOnly.js”.

      Alexander

  21. Hi Alexander,

    Thanks for the excellent script.

    I am using your script to hide & make read only SharePoint Columns. I can able to make all fields expect the SPFieldTaxonomyFieldType & SPFieldTaxonomyFieldTypeMulti.

    Did you updated your code “GetFieldValueOrSetAsReadonly.js” to support “SPFieldTaxonomyFieldType ” & SPFieldTaxonomyFieldTypeMulti.

    Please consider my request to include above fieldtype in your code

    Thank You

  22. Hi Alexander,

    Thanks for this wonderful website.

    I have a problem when i set fields. I have 4 fields side by side thanks to your method (customSideBySide()), but i would like to set one field of them but doesnt work: it sets all of my fields, and i don’t want to; They are connected i assume.. I’m not good at Js :(.

    Thanks for helping.

    Cherif,

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

    Thanks,
    Osmita

  24. Thank you very much for the great post!!

    It seems that the rich text field can only be made read-only when it has text in it. If it is empty, it can not be read-only.

    Can you please let me know how to fix this?

    Thank you very much!

      1. yes, I have updated.

        I added below scripts before arrToMakeReadOnly and it worked. (column Control_x0020_Link is enhanced multiline text, and it’s optional)

        var control_link = getFieldValue(‘Control_x0020_Link’);
        //alert(control_link);
        if (control_link == “”) {
        fields = init_fields_v2();
        setFieldValue(‘Control_x0020_Link’, ” “);
        }
        arrToMakeReadOnly = [‘Risk_x0020_Id’, ‘Control_x0020_Id’, ‘Control_x0020_Description’, ‘Prevention_x0020_Effectiveness’, ‘Correction_x0020_Effectiveness’, ‘Control_x0020_Type’, ‘Control_x0020_Link’];

Leave a Reply to Alexander Cancel reply

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