Working with SharePoint People Pickers with jQuery: A New Function Called findPeoplePicker

[notice]2012-09-07 – Note that I’ve added a more robust version of this function into SPServices v0.7.2, which at this writing is in beta but will be released soon. See the docs for SPFindPeoplePicker.[/notice]

I was working with several People Pickers in a form for a client project last week where I needed to set or get their values at various times in the page lifecycle. These things are pesky little compound controls, I often need to find them in the page, and I get tired of writing new script every time I want to do it. I’ve posted in the past about how to get the value with JavaScript, set the value with JavaScript, set one with jQuery, and more. It seemed high time to just write a little function to give me everything I needed in one go.

Here’s what I came up with:

[important]UPDATE 2012-04-24 – I made a dumb mistake by using :contains() in the selector for thisRow, which occasionally returned unwanted results. I fixed it with the .filter() function below.[/important]

// Find a People Picker in the page
// Returns references to:
//   row - The TR which contains the People Picker (useful if you'd like to hide it at some point)
//   contents - The element which contains the current value
//   currentValue - The current value if it is set
//   checkNames - The Check Names image (in case you'd like to click it at some point)
$.fn.findPeoplePicker = function(options) {

  var opt = $.extend({}, {
    peoplePickerDisplayName: "",	// The displayName of the People Picker on the form
    valueToSet: "",			// The value to set the People Picker to. Should be a string containing each username or groupname separated by semi-colons.
    checkNames: true			// If set to true, the Check Names image will be clicked to resolve the names
  }, options);

  // Find the row containing the People Picker
  var thisRow = $("nobr").filter(function() {
    return $(this).text() == opt.peoplePickerDisplayName;
  }).closest("tr");
  var thisContents = thisRow.find("div[Title='People Picker']");
  var thisCheckNames = thisRow.find("img[Title='Check Names']:first");
  if(opt.valueToSet.length > 0) thisContents.html(opt.valueToSet);
  if(opt.checkNames) thisCheckNames.click();
  var thisCurrentValue = thisContents.text();

  return {row: thisRow, contents: thisContents, currentValue: thisCurrentValue, checkNames: thisCheckNames};
}

This function doesn’t just find the People Picker in the form, it also allows you to set it and, if you choose, click the Check Names image automagically. It also returns a JSON object which contains references to the important elements which make up the People Picker so that you can work with them later. Unfortunately, the only thing I can key on to find the darn things in the page is the <nobr> element which contains the DisplayName of the column. There’s just not anything else in the People Pickers which distingishes them from each other other than the standard comment, like so:

<!--  FieldName="Site Contact"
			 FieldInternalName="Site_x0020_Contact"
			 FieldType="SPFieldUser"
		   -->

Uising that comment has always seemed even less reliable to me than the DisplayName, even though I select for it in SPServices in several places. (If I’m missing something, please let me know.)

Here are a few example calls:

// Set the Site Contact to the current user
siteContactPeoplePicker = $().findPeoplePicker({
  peoplePickerDisplayName: "Site Contact",
  valueToSet: $().SPServices.SPGetCurrentUser()
});
// Find the Stakeholders People Picker in the form for later us
stakeholdersPeoplePicker = $().findPeoplePicker({
  peoplePickerDisplayName: "Stakeholders",
  checkNames: false
});

In the first call, I’m setting the Site Contact to the current user and resolving the name. In the second call, I’m getting references to the important objects for the StakeHolders People Picker so that I can set the value variably later, like so:

// Set the Stakeholders column value
stakeholdersPeoplePicker.contents.html(stakeholderNames);
stakeholdersPeoplePicker.checkNames.click();

I think some variation of this would be helpful to add to SPServices, even though it has nothing to do with the Web Services. Would you use it? What else would you want it to do?

Similar Posts

62 Comments

  1. Definitely using and loving it! This is pure laziness speaking but it would be great if you could add a property that would let you set whether to exclude it from the SharePoint SpellCheck.asmx. I know it is a simple task now that I have this great selector to set the class and attributes but would be great “out-of-the-box” functionality.

  2. Hi Marc,

    I would like to disable the people picker in my form depending on some conditions. How do I disable this?

    Thanks in advance!

    Edwin

  3. Hi,
    i have a list A, there i have people picker employee, there will be on entry for each employee, i want to pull the items ID (A lists item ID) of the logged user through jquery, how can i do that?

    1. Shiva:

      You’d have to write something custom to handle that. You could do it woth script by testing the value on blur.

      M.

  4. hey, im pretty new to working with the control and have no clue on how to do it. what do you mean by blur? and im looking to validate it through the PP itself. any methods you know off?
    btw this is regarding the 2013 Client People Picker.

    1. Shiva:

      There’s nothing out of the box to exclude the current user from the People Picker. You’ll need to write something custom to handle it, whether it be script or managed code.

      M.

  5. Hi, my problem seems to be easy but i’m really blocked. I just want to get the value of a people picker and show it in an alert using javascript thanks for help

      1. I just found the function that sets a value in the people picker but i need the one that gets its value

          1. i found this syntax
            $().SPServices.SPFindPeoplePicker({
            peoplePickerDisplayName: “”,
            valueToSet: “”,
            checkNames: true
            });

            can i change the arguments or remove the valueToSet ?

            1. If you read the docs a little more closely, you’ll see that the function passes you back an object containing the current value, whether you set it or not.

              M.

  6. Marc,
    I am trying to get this working on SharePoint 2013 people picker, but with no luck. Tried to debug and found that there is no div with title=’People Picker’ also no img with title=’Check Names’. Can you please help?

Leave a Reply

Your email address will not be published. Required fields are marked *

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