newitem.aspx opening into the popup, so where do I need to add Content editor webpart. While opening newitem form, I need to autopopulate current user Name into sigle line text field?
3 Answers
You can use REST API to get the current user login name and append that value to the SharePoint text field using jQuery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type=text/javascript>
window.onload = function () {
var userDisplayName = '';
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
headers: { Accept: "application/json;odata=verbose" },
aync:false,
success: function (data) {
try {
//Get properties from user profile Json response
userDisplayName = data.d.DisplayName;
$('#ctl00_ctl63_g_31e84c00_425a_4193_9323_01cf5f3fd8e9_ff11_ctl00_ctl00_TextField').val(userDisplayName).prop('readonly', true).css('background-color', 'lightgrey'); // change the id of textfield (just inspect element your form and copy the id)
}
catch (err2) {
}
},
error: function (jQxhr, errorCode, errorThrown) {
alert(errorThrown);
}
});
}
</script>
Just add this code in your NewForm.aspx page.
-
-
@user47524 You can open the newform.aspx in SPD and insert this in <script></script>. Also, don't forget to load the jquery , sp.js files OR you can edit the newform.aspx page and insert the script in Script Editor webpart Oct 3, 2018 at 8:00
-
Thanks Sohail....I got it. I will add this code into the <script></script>. how would I need to load jquery , sp.js files. ? any code line I need to include into the <script></script>? Oct 3, 2018 at 8:03
-
Just add this code in newform.aspx and if you get any error related to jQuery then add the reference of jQuery file before this code. Oct 3, 2018 at 9:09
-
added same code into Script Editor webpart, but no luck.User name is not populationg Oct 3, 2018 at 11:12
Check this out once ...
var selectedActivity;
$(document).ready(function(){
$("input[Title='Name']").attr("disabled", "disabled");
populateCurrentUser();
});
function populateCurrentUser() { var currentUserId; var currentUserName; var userLoginName; var peoplePickerFieldName = "People Picker"; $.ajax({ url: "https://xyz.sharepoint.com/ListName/_api/web/currentUser", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, async: false, success: function (data) { currentUserId = data.d.Id; currentUserName = data.d.Title; //userLoginName = data.d.LoginName; }, error: function (error) { alert(error); } }); $("input[Title='Name']").val(currentUserName);
}
function PreSaveAction() {
$("input[Title='Name']").attr("disabled",false);
return true;
}
You can use _spPageContextInfo in your JavaScript code Add below line in your document.ready function
$("input[Title='Title Required Field']").val(_spPageContextInfo.userDisplayName);