Pre-populate ListFields on a SharePoint form

I needed to prepopulate a field in a SharePoint form with the value passed in from a QueryString. 

I needed to do this as i wanted to create a lookup to an item in another list, so I am passing in a QueryString value called PostID. This will be the ID of the item in the other list that I want to act as a lookup field.

Add the following code to the page header (on a page such as NewForm.aspx). I actually created a new page which contains the new item list form, so I put this code on that page.


<script language=”javascript” for=”window” event=”onload”>var elems = document.getElementsByTagName(“INPUT”);var PostID=””;var queryString = document.location.search.split(“&”);for (var i=0;i<queryString.length;i++) { if ((queryString[i].split(“=”)[0]==”PostID”) || (queryString[i].split(“=”)[0]==”?PostID”)) PostID=queryString[i].split(“=”)[1]; }for (var i=0;i<elems.length;i++) { if (elems[i].name==”OWS:Post:Local”) elems[i].value=PostID;}</script>

This looks for the QueryString value PostID and if it finds it, it search the INPUT items on the page for one calledPost and sets that form field to be the value passed in from the QueryString.

Post is the name of my List Column, so change that to whatever field you want to prepopulate. Also change the OWS:Post:Local bit to be the name of your column, so change Post to Title or whatever is appropriate. If you want to preset URL’s then you can use OWS:URL:URL and OWS:URL:DESC to set the 2 URL components.

The javascript could be tidied up a bit, you may notice that I search for PostID or ?PostID, this is because if PostID is the first QueryString item then it gets read with the ?. I just haven’t changed it yet.

I got the initial code for this from here: MSD2D and adapted it to my needs.

Published by

Mark Stokes

I am a SharePoint Server MVP and the founding Director of Red Plane, a Microsoft Silver Partner in the North West of the UK. I am interested in Travel, Extreme Sports, Photography, Technology, Gadgets, Raspberry Pi and, of course, SharePoint! Note: This is my personal blog and entries may not represent the views of my employer.

Leave a Reply

Your email address will not be published. Required fields are marked *