Thursday, March 24, 2011

Get current SharePoint User with JavaScript

During the SharePoint form customization in many cases it is important to know the current user. So with JavaScript and SharePoint Designer this is how it's done:

var loginElement = document.getElementById("zz7_Menu").innerHTML;
var end = loginElement.indexOf("<");
var nameOnly = loginElement.substring(8, end);

note: I use this script in MOSS2007, but if you use this in WSS3 change "zz7_Menu" to "zz6_Menu".

My whole point using this script was to get the current username (in my case organization username format is: username14, username57 etc.) And based on that I need to get only numbers from this username. So there is my complete solution:

var loginElement = document.getElementById("zz7_Menu").innerHTML;
var end = loginElement.indexOf("<");
var nameOnly = loginElement.substring(8, end);
var number = nameOnly.replace (/[^\d]/g, "");
var k;

if (number != "") {
var elements = document.getElementsByTagName('select');
for (var i = 0; i < elements.length; i++) {
if (elements[i].title == 'YOUR DROPDOWN TITLE'){
var sel = elements[i].options.selectedIndex = number;
for (k=elements[i].options.length-1;k>=0;k--) {
if (k != sel) {
elements[i].remove(k);
        }
      }
    }
  }

}

2 comments:

  1. Hi Koncis: First I appreciate your work. Coming to your code : In each and every sharepoint page there is People picker (like: Welcome Domain\koncis). Developers can get that people picker id by using developer tool(IE 8).

    If you want to know the logged on user roles and permissions we can use SPAPI_UserGroups.js
    files right.

    ReplyDelete
    Replies
    1. Hi & thx for suggestions and your comments!

      Delete