I have a list field named PersoniKonfirmues
and I want this field to be set to the current user that is logged in. I want to do this with client side using javascript in Sharepoint 2013
Please help me.
Add the below code in Script Editor WebPart
in your NewForm
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// Wait until SP.JS has loaded before calling getWebUserData
ExecuteOrDelayUntilScriptLoaded(SetCurrentUsernameToPeoplePicker, "sp.js");
});
function SetCurrentUsernameToPeoplePicker()
{
var ctx = new SP.ClientContext.get_current();
this.website = ctx.get_web();
this.currentUser = website.get_currentUser();
ctx.load(currentUser);
ctx.executeQueryAsync(Function.createDelegate(this, this.onSucceess),
Function.createDelegate(this, this.onFail));
}
function onSucceess(sender, args)
{
var loginName = currentUser.get_loginName();
var form = $("table[class='ms-formtable']");
var userField = form.find("input[id$='ClientPeoplePicker_EditorInput']").get(1);
var peoplepicker = SPClientPeoplePicker.PickerObjectFromSubElement(userField);
peoplepicker.AddUserKeys(loginName);
}
function onFail(sender, args)
{
alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}
</script>
[Output] (Tested on My Side)
Note: In case you want to set
People
Field (not People1), just setget(1)
toget(0)
if you have multiplePeople and Picker
field just set#OrderID
inget(#OrderID)
based on the order ID of your desiredPeople and Picker
field on your form
var userField = form.find("div[id$='PersoniKonfirmues']").get(0);
Commented
Dec 3, 2017 at 8:50