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”):
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:
<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"> // Array of FieldInternalNames to make readonly var arrToMakeReadOnly = ['Title','MySelect','MyPeoplePicker','Lookup','Bool','Hyperlink','DateTime','Multiline']; // The function call must be wrapped in the "$(document).ready" to work with complex field types $(document).ready(function(){ readOnlyFieldArray(arrToMakeReadOnly); }); </script>
The above code sets all fields in the array “arrToMakeReadOnly” as readonly. To simply get a fields value, do it like 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 myValue = getFieldValue("Insert the FieldInternalName of your field here"); }); </script>
To get a fields value in DispForm, do it like 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"> var myValue = getFieldValue("Insert the FieldInternalName of your field here","disp"); </script>
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 "SPFieldUserMulti" 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: <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="/test/English/Javascript/readOnlyForSharepointFields.js"></script> <script type="text/javascript"> // Array of FieldInternalNames to make readonly var arrToMakeReadOnly = ['Title','MySelect','MyPeoplePicker','Lookup','Bool','Hyperlink','DateTime','Multiline']; // The function call must be wrapped in the "$(document).ready" to work with complex field types $(document).ready(function(){ redOnlyField(arrToMakeReadOnly); }); </script> */ function readOnlyFieldArray(arrayOfFieldInternalNames){ $.each(arrayOfFieldInternalNames,function(i,fin){ var fieldValue = getFieldValue(fin); if(!fieldValue)return false; thisField=$(fields[fin]); // Strip off any "formvalidation star" thisField.find('.ms-formlabel span.ms-formvalidation').remove(); // Set as "readOnly" thisField.find('td.ms-formbody').hide().after("<td class='ms-formbody' style='width:450px'>"+fieldValue+"</td>"); }); } 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 "edit_OR_disp" is undefined, default to "edit" if(edit_OR_disp==undefined)edit_OR_disp='edit'; if(edit_OR_disp=='disp'){ // If "disp" var valRaw = $(fields[fin]).find('.ms-formbody').text(); return (valRaw.replace(/[ xA0]+$/,'')=='')?'':valRaw.replace(/[ xA0]+$/,''); }else{ // If "edit" var fieldType = $(fields[fin]).attr('FieldType'); if(fieldType==undefined){ alert("The attribute "FieldType" is missing.nEnsure the function init_fields() used is the one included in the file "GetFieldValueOrSetAsReadonly.js"."); 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>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('<br />'); break; case 'SPFieldUser': var myPeoplePicker = thisField.find("div[id='divEntityData']"); returnVal = myPeoplePicker.attr('displaytext'); returnVal = (returnVal!=undefined)?returnVal:''; break; case 'SPFieldUserMulti': var userMulti = []; thisField.find("div[id='divEntityData']").each(function(i,div){ thisVal = $(div).attr('displaytext'); if(thisVal!=undefined){ userMulti.push(thisVal); } }); returnVal = userMulti.join('<br />'); break; case 'SPFieldLookup': if(thisField.find('select').length>0){ returnVal = thisField.find('select option:selected').text(); }else{ returnVal = thisField.find('input').val(); } break; case 'SPFieldLookupMulti': var lookupMulti = []; thisField.find("select:last option").each(function(i,opt){ opt = $(opt); lookupMulti.push(opt.text()); }); returnVal = lookupMulti.join('<br />'); 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 = "<a href='"+link+"'>"+descr+"</a>"; 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]+/)+":"; 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+" "+hour+minutes+" "+AMPM; break; case 'SPFieldNote': returnVal = thisField.find('textarea:first').val(); break; case 'customHeading': returnVal = ''; break; default: returnVal = "Unknown fieldType: <strong>"+fieldType+"</strong>, please check the script."; } if(returnVal==='')returnVal="&nbsp;"; return returnVal; } } function init_fields(){ 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]).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.
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
simply amazing! This is great!
Hi – How can this field be set as Read only to specific sharepoint group and editable by another SharePoint Group.
Thanks in Advance
Siby
Hi,
Look at this one Showing or hiding list fields based on membership in a SharePoint group.
You should be able to figure it out from this article.
Alexander
Alex – Thanks for the reply.
How do you call the function? I am nort getting any result back.
The article has examples of CEWP-code to implement the solution in the top three code blocks.
What exactly is the problem?
Alexander
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!
Alexander, here is an example how I placed the code in CEWP.
function id2() {
var myValue = getFieldValue(“Title”,”disp”);
retrun myValue;
}
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);
}
I am sorry. here is the full code
function id2() {
var myValue = getFieldValue(“Title”,”disp”);
window.alert(myValue);
}
What is happening? I don’t see my posting posted. Is there a limit?
The comments were held for moderation. I have approved them now.
Alexander
function id2() {
var myValue = getFieldValue(“Title”,”disp”);
window.alert(myValue);
}
Hi,
What kind of value do you get back when alerting “myValue”?
Take a look at this one: How to troubleshoot when the scripts does not work and assure that jQuery is loaded.
Alexander
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!
Great code, real neat! Thanks a bunch, you are the man!
🙂
Wonderful code. Works great. Thank you very much for sharing.
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.
Hi,
Try this:
Alexander
Hi Alexander,
It works well 🙂 with this condition.
Let’s capitalize on this!!!
Thanks again.
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
Hi, I would guess the FieldInternalName is wrong… Look here
Alexander
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.
Hi,
Put this code in a CEWP below the form:
Replace the FieldInternalName “Status” with your own FieldInternalName.
Alexander
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
Ok, so about the date, I fix it without date and time but also Date!
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
Hi Alexander,
Thanks for your help.
I’m gonna try this solution straight away!!
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
Hi,
I’m not quite sure which fields you are trying to hide, but look at this post: Dynamic expand/collapse fields or array of fields it should give you some hints on how it is possible.
Hiding fields is just a few lines – as long as you use the function init_fields() from the article.
Alexander
Is it possible to hide fields based on the selection of the content type drop-down?
Scott
Look at this article and see if it helps you on the way
Alexander
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?
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?
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?
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
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
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
Why doesn’t it work with Mozilla Firefox??
It alerts ‘The attribute “FieldType” is missing.’
Hi,
I have updated the function init_fields() as Firefox has made some changes in newer versions.
Alexander
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..:)
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
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!
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
sorry alexander,
the comment landed out of this thread..
The only modification I did was adding the first piece of code to the EditForm.aspx under
I didn’t add any webpart.
Have you put the code below the form webpart?
If it is placed above it will not work.
Alexander
I’ve added finally a CEWB below my editForm webpart.
Where should I put the code?
In source editor of the CEWB??
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
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..
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
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.
Hi,
Follow the link in the top of the article to find an updated version of the function “getFieldValue”.
Alexander
Trying this method currently on a lookup 20+ items, getting “Unknown fieldType: SPFieldLookup_Input, please check the script.” any advice?
Read the note in the top of the article – these scripts have been updated.
Alexander
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.)
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:
Alexander
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!
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.
Hi,
You must follow the link in the top of the article and get an updated version of the function “getFieldValue”.
Alexander
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);
oops I think I understand now…you are replacing the GetFieldValueOrSetAsReadOnly.js file with the spjs-utility.js file correct?
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
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
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
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,
Thanks for this useful post. It is excellent.
Please let me know how to get value of ‘SPFieldTargetTo’ type. Appreciate your help.
Thanks,
Osmita
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!
Hi,
Have you updated to the latest version of spjs-utility.js? – it is linked in the top of the article.
Alexander
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’];
Hello Alex,
My code looks like this in edit form but im getting undefined as a result in alert pop-up. Kindly help here.
/sites/PSI/SiteAssets/JS/jquery-3.1.0.min.js
/sites/PSI/SiteAssets/JS/jquery.min.js
/sites/PSI/SiteAssets/JS/GetFieldValueOrSetAsReadonly.js
/sites/PSI/SiteAssets/JS/spjs-utility.js
fields = init_fields();
var a = getFieldValue(‘Title’);
alert(a);
Hi,
The scripts described in this article is 7 years old and this solution might not work in later versions for SharePoint.
Please have a look at DFFS instead: https://spjsblog.com/dffs/
Alexander