Hide Fields Using Permission Levels in SharePoint Using Java Script

Hello Everyone!

Welcome to a new important article for all developers of which we will hide the form fields based on their permission we require.

So suppose I have a form with 10 fields and I want a few of them to be only visible to certain users. So what will I do?

Let's hit the topic.

  • First create a group and keep all users you want to have access to all fields in a form in that group.
  • Other users who have access to the form but no access to those special fields can be added anywhere in the site to any permission level.
  • Now in that form add the following JavaScript code in new, edit as well as a view item.
  • For me I have hidden the Status, Any comments, reviewed By and Response fields for general users.
  • Now what I am doing is, I am calling sp services to check whether the logged in user is one among my "Request Team" group.
  • If he is not he will not be able to view edit or create the preceding fields.
  • But if he is one among the users in the group he will be able to see all other fields since he has special rights to see them.

Code

  1. <script type="text/javascript">      
  2. $(document).ready(function () {  
  3.   $("Select[title$='Status']").closest('tr').hide();  
  4. $("textarea[title$='Any Comments']").parent('span').parent('td').parent('tr').hide();  
  5. $("Select[title$='Reviewed By']").closest('tr').hide();  
  6. $("[title$='Response']").closest('tr').hide();  
  7.     $().SPServices({  
  8.         operation: "GetGroupCollectionFromUser",  
  9.         userLoginName: $().SPServices.SPGetCurrentUser(),  
  10.         async: false,  
  11.         completefunc: function (xData, Status) {  
  12.             if (($(xData.responseXML).find("Group[Name='Request Team']").length == 1)) {  
  13.               $("Select[title$='Status']").closest('tr').show();  
  14. $("textarea[title$='Any Comments']").parent('span').parent('td').parent('tr').show();  
  15. $("Select[title$='Reviewed By']").closest('tr').show();  
  16. $("[title$='Response']").closest('tr').show();  
  17.             }  
  18.         }  
  19.     });  
  20. });  
  21. </script> 

Don't you think it is a neat job rather than working on Infopath forms and setting up the rules?

Keep learning.

Cheers.

Up Next
    Ebook Download
    View all
    Learn
    View all