Sharepoint - In 2013 using JavaScript how do you empty a people picker field?
scenario:
when you enter form editing and has some user of this picker people, this is the "oldHtml"? (I'm finding this a bad practice)
try using this code:
var getIDPeoplePicker=$("div[Title='Column Name of the people picker here']").attr("id");
var ppobject = SPClientPeoplePicker.SPClientPeoplePickerDict[getIDPeoplePicker];
var usersobject = ppobject.GetAllUserInfo();
usersobject.forEach(function (index) {
ppobject.DeleteProcessedUser(usersobject[index]);
});
with this code will get id of the PP, People Picker Object, All users in specific PP and loop All users for deletion, and clear the field perfectly without edit html page. And you can add this code to button "Clear Field".
but before of use code, check your people picker id correctly.
Hope this helps.
Proposing some other solutions...
Given that you have a people picker called ppobject
:
var ppobject = SPClientPeoplePicker.SPClientPeoplePickerDict["my_peoplePicker_TopSpan"];
To delete the last user in the people picker, you can call
ppobject.DeleteProcessedUser()
This is ultimately what's happening in the accepted answer, for as many times as there are users (usersobject[index]
is undefined because index
is the user object itself, not a field within usersobject
).
Could be simplified as:
while (ppobject.TotalUserCount > 0) {
ppobject.DeleteProcessedUser();
}
DeleteProcessedUser()
is really looking for an HTML element as the argument, so another option is:
ppobject.IterateEachProcessedUser(function (index, user) {
// could add some filtering, e.g.,
// if (!/@mydomain.com$/i.test(user.UserInfo.EntityData.Email))
ppobject.DeleteProcessedUser(document.getElementById(user.UserContainerElementId));
});
Lastly, I found that after the last user is deleted, it will not show the initial help text -- you could use:
//if (ppobject.TotalUserCount == 0)
document.getElementById(ppobject.InitialHelpTextElementId).style.display = 'inline';
Assuming the name of people picker field is "user" then to clear do following
var oldhtml = ''
$(document).ready(function() {
//Saving how the initial picker control without any selection
oldhtml = $('div [id^="user_"]').html();
});
//To clear People Picker
$('div [id^="user_"]').html(oldhtml);
Note - This code is not tested. The logic is to save the HTML content of the picker control and reapplying saved html as part of clear process.