I found this great POST by the SharePoint Designer team for “Using Javascript to Manipulate a List Form Field”. Unfortunately it didn't work very well for People Picker fields which is exactly what I needed to do today.
After some trial and error, and a bit of head scratching I finally came up with the follow which I thought I'd share, since when I was searching for a solution I found a lot of people in a similar situation with no solution posted.
<script type="text/javascript">_spBodyOnLoadFunctionNames.push(
"fillDefaultValues");
function fillDefaultValues()
{
fillPeoplePickerWithCurrentUser('Submitted_x0020_By');
}
function fillPeoplePickerWithCurrentUser(pickerName)
{
//get the current user from the welcome menu
var currentUser = getCurrentUser();
//check to see that we've got it
if(currentUser !=
null)
{
//get the people pickers input div
var pp = getPickerInputElement(pickerName);
//set it to the current user if we've found it
if(pp !=
null)
pp.innerHTML = currentUser;
} }
function getCurrentUser()
{
var tags = document.getElementsByTagName('a');
for (
var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) ==
'Welcome')
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
} } }
function getPickerInputElement(fieldsInternalName)
{
var result =
"";
var divs = document.getElementsByTagName(
"DIV");
for(
var i=0; i < divs.length ; i++)
{
if(divs[i].id==
"WebPartWPQ2")
{
var tds = divs[i].getElementsByTagName(
"TD");
for(
var j=0; j < tds.length; j++)
{
var cellHTML = tds[j].innerHTML;
if(cellHTML.indexOf(
'FieldInternalName="' + fieldsInternalName +
'"') >= 0)
{
var innerDivs = tds[j].getElementsByTagName(
"DIV");
for(
var k=0; k < innerDivs .length; k++)
{
if(innerDivs[k].id.indexOf(
"UserField_upLevelDiv") > 0)
{
result = innerDivs[k];
break;
}
} }
}
}
}
return result;
}
</script>
. . .