In this blog, we will see how to check if the current user is present in specific group or not, using SPServices.

Recently, I faced one situation where I needed to show li element for some specific group of users. For that, we have the below HTML - UL LI structure and from that, we need to show the "Create" link only for admin users (Group Name: Category Owner).
  1. <div>
  2. <ul>
  3. <li id=”Category1”>Category1</li>
  4. <li id=”Category2”>Category1</li>
  5. <li id=”Category3”>Category1</li>
  6. <li id=”Category4”>Category1</li>
  7. <li id=”Category5”>Category1</li>
  8. <li id=”Category6”>Category1</li>
  9. <li id=”Category7”>Category1</li>
  10. <li id=”create”>Create Category</li>
  11. </ul>
  12. </div>

The above structure is being created on the landing page of my site. Apart from that, I don’t want to show "Create Category" button to all the users. I have created one SharePoint group called “Category Owners” and added users into it.

In document.ready function, I have added the below code to load SPServices.

  1. <script>
  2. $(document).ready(function() {
  3. insureSPServices(InitializePage);
  4. });
  5. insureSPServices
  6. function is used to make sure SP Services is loaded
  7. function insureSPServices(callbackFunction) {
  8. if ($().SPServices == null) {
  9. jQuery.getScript("/_layouts/15/Project /Scripts/jquery.SPServices-0.7.2.js", callbackFunction);
  10. } else {
  11. callbackFunction.call(null, "Already Loaded");
  12. }
  13. }
  14. function InitializePage(data, textStatus) {
  15. isGroupMember("Category Owners ", function(result) {
  16. if (result) {
  17. // Code for when current user is in the group
  18. document.getElementById("create").style.display = "block";
  19. }
  20. });
  21. }
  22. function isGroupMember(groupName, callback) {
  23. $().SPServices({
  24. operation: "GetGroupCollectionFromUser",
  25. userLoginName: $().SPServices.SPGetCurrentUser(),
  26. async: false,
  27. completefunc: function(xData, Status) {
  28. callback($(xData.responseXML).find("Group[Name='" + groupName + "']").length == 1);
  29. }
  30. });
  31. };
  32. </script>