Set "peoples or groups" field with current user "login name" in sharepoint list form using javascript

hi friends
i am trying to set peoples or groups field in sharepoint  list form with current user login name
here my code
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script type="text/javascript">
$(document).ready(function NewItemView () {
var currentUser;
    if (SP.ClientContext != null) {
      SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js');
    else {
      SP.SOD.executeFunc('sp.js', null, getCurrentUser);
    function getCurrentUser() {
      var context = new SP.ClientContext.get_current();
      var web = context.get_web();
      currentUser = web.get_currentUser();
      context.load(currentUser);
      context.executeQueryAsync(onSuccessMethod, onRequestFail);
    function onSuccessMethod(sender, args) {
      var account = currentUser.get_loginName();
      var accountEmail = currentUser.get_email();
      var currentUserAccount = account.substring(account.indexOf("|") + 1);
    SetAndResolvePeoplePicker("requester",account);
// This function runs if the executeQueryAsync call fails.
    function onRequestFail(sender, args) {
      alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());
 function SetAndResolvePeoplePicker(fieldName, userAccountName) {
   var controlName = fieldName;
    var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");
    var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
    var spPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
    peoplePickerEditor.val(userAccountName);
    spPeoplePicker.AddUnresolvedUserFromEditor(true);
</script>
but it is not working
please help me

Hi,
According to your post, my understanding is that you wanted to set "peoples or groups" field with current user "login name" in SharePoint list form using JavaScript.
To set "peoples or groups" field with current user "login name”,  you can use the below code:
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script type="text/javascript">
function SetPickerValue(pickerid, key, dispval) {
var xml = '<Entities Append="False" Error="" Separator=";" MaxHeight="3">';
xml = xml + PreparePickerEntityXml(key, dispval);
xml = xml + '</Entities>';
EntityEditorCallback(xml, pickerid, true);
function PreparePickerEntityXml(key, dispval) {
return '<Entity Key="' + key + '" DisplayText="' + dispval + '" IsResolved="True" Description="' + key + '"><MultipleMatches /></Entity>';
function GetCurrentUserAndInsertIntoUserField() {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
this._currentUser = web.get_currentUser();
context.load(this._currentUser);
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
function onSuccess(sender, args) {
SetPickerValue('ctl00_m_g_99f3303a_dffa_4436_8bfa_3511d9ffddc0_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_UserField', this._currentUser.get_loginName(),
this._currentUser.get_title());
function onFaiure(sender, args) {
alert(args.get_message() + ' ' + args.get_stackTrace());
ExecuteOrDelayUntilScriptLoaded(GetCurrentUserAndInsertIntoUserField, "sp.js");
</script>
More information:
http://alexeybbb.blogspot.com/2012/10/sharepoint-set-peoplepicker-via-js.html
Best Regards,
Linda Li
Linda Li
TechNet Community Support

Similar Messages

  • Set metadata field with current user

    I would like to have a Response that would set a field with the current logged in user. (This would be triggered by a Subscription)
    I am using a Response Action of "Set Asset Metadata".
    I have tried entering:
    [Name]
    [USER_NAME]
    [Username]
    and so on but the field just puts in the text not the user. Is it not possible to copy from one metadata field to another in a Response Action?

    Variable insertions only work for fields that are part of the Asset, Production, or Job that is triggering the Subscription. The only one of those that would reference a user is a Job Subscription. Jobs have a field called \[Owner] that lists the user that caused the job to happen. Of course, this is only viable for actions that cause a job to occur, such as downloads, exports, analysis, archive, or recovery.
    Unfortunately, Set Asset MD will not be of any use in a Job Subscription since there is no asset to set metadata upon when you are subscribing to a job. Long story short, you will not be able to do what you are describing automatically.

  • I am currently an iPhone user, and I am planning to upgrade to a galaxy s5. Will I still be able to group message with iPhone users even thought I have a galaxy

    I am currently an iPhone user, and I am planning to upgrade to a galaxy s5. Will I still be able to group message with iPhone users even thought I have a galaxy

    Hi
    Yes you should be able too, this depends on the features on the phone but i would imagine something as new as the s5 would have this feature. However this would obviously be over standard sms rather than imessage.
    Hope this helps

  • How to update a People and group field using a sandbox solution

    Hi,
    I am creating a sandbox solution for office 365 and creating a custom form using visual web part, which will allow users to enter data in a custom list.
    And that list also have a user field. I am able to get SharePoint user field on the form (using javascript) which is searching for the user and get a value (working fine).
    Issue: But I am not able to save the user value. Because to save user value I require web, UserID and login name, to construct SPFieldUserValue object or string in "111;#TestUser" format. Moreover that user should be present in
    SiteUserInfoList. 
    I tried web.EnsureUser() but did not work under sanbox solution.
    Can you please provide any pointer or workaround to the problem? I may be missing something here.
    Thanks,
    Himanshu

    Hi,
    According to your description, my understanding is that you want to update the people and group field in Sandbox solution.
    In the sandbox solution, you can still use the web.EnsureUser() function to get the user information, see the thread below:
    EnsureUser in sandboxed solution
    In additional, there is a demo with your similiar requirement for your reference:
    Using the People Picker Control in Sandbox Solutions / Office 365
    Thanks
    Best Regards,
    Jerry Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • How to get List of SharePoint Groups to which Current Users belongs using Javascript ?

    How to get List of SharePoint Groups to which Current Users belongs using JavaScript? Not JSOM

    Here is the code that worked for me:
    var userid= _spPageContextInfo.userId;
      var requestUri = _spPageContextInfo.webAbsoluteUrl + '/_api/web/CurrentUser/Groups?$select=Id,Title';
    alert(requestUri);
      var requestHeaders = { "accept" : "application/json;odata=verbose" };
      $.ajax({
        url : requestUri,
        contentType : "application/json;odata=verbose",
        headers : requestHeaders,
        success : onSuccess,
        error : onError
      function onSuccess(data, request){
    var s='';
     for (var i = 0; i < data.d.results.length; i++)
    s +=data.d.results[i].Title+'\n';
        alert(s);
      function onError(error) {
        alert("error");

  • When trying to download it pops up with a window saying with current user i may not be able to do everything and is asking for administrater password or continue with current user? when i click current user it does nothing and i dont know the password

    when trying to download it pops up with a window saying with current user i may not be able to do everything and is asking for administrater password or continue with current user? when i click current user it does nothing and i dont know the password
    == User Agent ==
    Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)

    Not from your end. Click here and ask the iTunes Store staff for assistance.
    (126716)

  • How can I filter a Sharepoint 2007 libarry list based on current user login?

    Hi all.
    I would like to know how I can filter a SharePoint library list based on current user login.
    Suppose I have created the followings:
    1) A SharePoint form library containing bunch of uploaded InfoPath form data.
    2) The InfoPath form template contains a promoted text field called "TargetUser" to store user domain login (ex: DOMAIN\JOE) and every InfoPath form file in the library has a valid domain name stored in the "TargetUser" field.
    I have created a custom view for the form library and would like to filter this view so only items whose "TargetUser" field matches current user's login ID are displayed.
    I went to Edit View page to customize the view and tried to use the [Me] function but I got a "Filter value is not a valid text string" message instead when clicking OK. Apparently [Me] returns a Person/Group data type and the filter cannot compare its value
    to that of "TargetUser".
    I tried using text functions (ex: TEXT([Me],"") hoping to extract default string value from [Me]. The filter accepts the parameter without any error but the resulting fitlered list does not display any items at all.
    I have googled this subject for hours but I have not found any solution.
    It would be greatly appreciated if anyone can help me to create a functional filtered list.
    FYI, my SharePoint 2007 installation is just WSS 3.0 + Form Server. I do not have MOSS 2007 (so no MOSS 2007 web parts or web services).
    Thank you.
    Jason

    Here's what I usually do in order to accomplish this.  Ultimately you'll need to have 2 different fields.  There's the one you already have, with DOMAIN\username stored in it.  Then you'll need an additional field as a "person" column type. 
    Call it "TargetPerson" or something.
    Create a sharepoint designer workflow that runs each time an item is created or changed.  One action:
    Set FIELD to VALUE.
    The first FIELD is "TargetPerson", the VALUE is your "TargetUser" field. 
    Once this is done, then the person value is stored in the person field.  This is the field that you can filter by "TargetPerson" is equal to [Me]
    Laura Rogers, MCSE, MCTS
    SharePoint911: SharePoint Consulting
    Blog: http://www.sharepoint911.com/blogs/laura
    Twitter: WonderLaura

  • Preoblem with Browse facility in Terminal Server with Normal User Login!!!

    Hii All,
           I am facing a problem with my addon in which I am using browsing facility.
           But the Browse facility is working properly  in Terminal Server with Administrator Login, but not working in Terminal Server with Normal User Login.
           So how it can be solved?
    Thanks & Regards,
    Nabanita
    Edited by: ghosh.nabanita on Aug 9, 2011 12:47 PM
    Edited by: ghosh.nabanita on Aug 9, 2011 1:46 PM

    Hi,
    You have to check group polices if browsing is enabled.
    Check this thread:
    http://social.technet.microsoft.com/Forums/en-US/winserverGP/thread/336377db-e0cb-4c8e-b7c7-01b7c11c0e27/

  • I had renamed my user login name and assumed that there will be no change in the settings and files. When I login with the new profile name everything is gone. How can I get back all my files and settings?

    I had renamed my user login name and assumed that there will be no change in the settings and files. When I login with the new profile name everything is gone. How can I get back all my files and settings? Please help. Thanks.

    You should have asked this before you tried: Changing username or short name- User Account and Short Name- OS X- How to change user account name or home directory name.

  • How to seperate current page fields in a pdf form using javascript

    Hi,
    Is that possible to seperate current page fields(textbox, Chesckbox) in a pdf form using javascript.
    I have coding to get all the fields in a pdf form. But i want to take CURRENT PAGE alone.
    Please help me out.
    Thanks and regards,
    Christy

    Hi try67,
    Thanks for your support.
    I got the result.
    Thanks and Regards,
    Christy

  • I would like to set up an older iPad with a new messages account so it can be used by my kids.  I don't, however, want to lose the apps or music that are on the iPad. Can I change only the Messages "account"?

    I would like to set up an older iPad with a new messages account so it can be used by my kids.  I don't, however, want to lose the apps or music that are on the iPad. Can I change only the Messages "account"?

    Thanks. I had tried that, but was still having problems. Then I realized that I was using three addresses on both devices.  Once I changed it to only one email on one iPad and a different email on the other, it worked great. Your message encouraged me to dig deeper and think differently. It worked. Thanks again!

  • HT1492 Hmm, I was deleting some files last night and when I came to booting up this morning my Macbookpro (5 years old) i was greeted with a user login screen? put in my password, but all i get is the space screen and no further action...? cant get apps o

    mm, I was deleting some files last night and when I came to booting up this morning my Macbookpro (5 years old) i was greeted with a user login screen? put in my password, but all i get is the space screen and no further action...? cant get apps o my bar

    Sounds like you may have deleted something you shouldn't have. Boot to an OS X DVD or a bootable backup, and using Disk Utility, do a repair disk, and while there repair permissions. Disconnect any peripherals, and reboot. If you get the same startup behavior, do a safe boot, by holding the shift key down when booting. If that works, try a normal boot. If neither step helps, you may need to relaod your operating system.

  • How to get and set the column order in SharePoint list forms

    Hi,
    I want to read the column order of the SharePoint list forms in SharePoint 2003 sites using any of the available web services and need to set the same order
    in the newly created list in SharePoint 2010.
    I am able to read the fields from SharePoint 2003 and creating the list with same fields in SharePoint 2010, but the column order is not maintaining in
    list forms.
    Also, I need to created the views from 2003 site to 2010 site.
    Please help me...
    Thanks in advance...

    Hi,
    Please try to use the following code to programatically change the order.
    SPList list = web.Lists["Example List"];
    if (list.ContentTypes.Count > 0)
    SPContentType ct = list.ContentTypes[0];
    string[] names = {"Example_x0020_One", "Example_x0020_Two", "Example_x0020_Three"};
    ct.FieldLinks.Reorder(names);
    ct.Update();
    Here is a similar thread for your reference:
    https://social.technet.microsoft.com/Forums/en-US/ce66fd65-2882-4bda-8142-89e116d8b90f/how-to-set-the-order-of-the-fields-in-list-forms?forum=sharepointdevelopmentprevious
    Best Regards
    Dennis Guo
    TechNet Community Support

  • # How to get the system AD Domain user login name in portal?

    when a system user use AD Domain method login the system.
    and then the user open the portal web application page, but not use AD Domain name login in portal page, that time ,I want to catch the user system login name show in portal page?
    I hava try the sereval method with Java or Jsp, or User Cookies ActiveX pulg,I get only the name of the portal hostname.
    so Anyone will provider me a well method to get the user login name?

    Elobrate more on ur problem

  • On start up I get the message "C:\users\login name\Appdata\local\temp\225704Log.in iiss Lost"

    on start up I get the message "C:\users\login
    name\Appdata\local\temp\225704Log.in iiss Lost"
    I've gorn though so many discussions on this trying to fix it I've
    do everything and it is still poping up every time i turn my desktop on what do i do?

    Hi,
    The suggestion provided by Maffiow is worthy to try. Msconfig can tell you some on things loaded on startup. Do any of the items listed refer to that file?
    In addition, it states that your windows 7 is missing some system files. And definitely it would be some important to file to your windows. You better check it with performing a Clean Boot.
    How to perform a clean boot to troubleshoot a problem in Windows 8, Windows 7, or Windows Vista
    http://support.microsoft.com/kb/929135
    The path which you have shown here is a path for temporary file. I think there will be something wrong with your system temp folder. For this Clear the redundant files in temporary folder. You can do this by performing the following steps.
    a. Restart the computer to Safe Mode.
    b. Click Start and click Control Panel.
    c. Click Classic View and choose Folder Options.
    d. Click View tab, choose Show hidden files and folders box, click Apply and click OK.
    e. Click Start -> Computer.
    f. Go to C:\Users\your user name\AppData\Local\Temp folder.
    g. Select all files in the Temp folder and delete them. Click Yes when prompted.
    h. Restart the computer to Normal Mode for a test.
    Hope it helps.
    Regards,
    Blair Deng
    Blair Deng
    TechNet Community Support

Maybe you are looking for