Pre-Populating SharePoint Fields

What if you needed to pre-populate your SharePoint fields with data based on user selection?

For example if a user’s selected country is Australia, then the Country field on your EditForm.aspx page will be pre-populated with the value Australia.

You can achieve this through QueryStrings and jQuery/JavaScript.

In my example I simply directed the user to a page via-URL with QueryString, such as below:

http://intranet/Pages/default.aspx?Country=Australia

.aspx?=.aspx?=http://<url>.aspx?<FieldName>=<UserSelectedValue>

Where <FieldName> is the Internal field name and NOT the display name, and <UserSelectedValue> is a value obtain from a user’s input, such as a textbox, drop-down list, checkbox etc etc.

NOTE: It is important to check for special characters and change them accordingly. For example, a space is replaced with %20

Once you have the <FieldName> and <UserSelectedValue>, you can then retrieve them and populate the SharePoint field quite easily. Basically, you will need to grab the URL from the current location, then separate your QueryStrings into an Array, as you may have more then one NameValue pair. You will then need to iterate through the Array find the relevant <FieldName> and use it’s corresponding <UserSelectedValue> on the SharePoint field. In my example the snippet is as below:

<script type="text/JavaScript">
    $(window).load(function() {

// Get URL from the current location, then separate your QueryStrings into an Array

var queryString = location.search.replace(‘?’, ”).split(‘&’);

        // iterate through the Array find the relevant <FieldName> and use it’s corresponding
       // <UserSelectedValue> to update the SharePoint field
        for(var i=0; i<queryString.length; i++)
        {
            var value = queryString[i].split(‘=’)[1];
            if(queryString[i].split(‘=’)[0] == "Policy")
            {
                $("#<SharePointFieldControlID>").val(value);
            };
        };
    });
</script>

NOTE: Remember to check for special characters and change them accordingly.


jQuery for OnLoad event?

What’s the closest thing in jQuery to replicate JavaScript’s OnLoad event? Well it’s quite possible to just use document.ready as below:

$(document).ready(function() {

       // code goes here

});

Unfortunately, this does not work as intended for me. Especially in cases where I had to work on SharePoint. In order to overcome it, I used the window.load instead. See below:

$(window).load(function() {

     // code goes here

});


Follow

Get every new post delivered to your Inbox.