How to Get the Query String from the URL and Set the Form field value?

Get the Query String from the URL

From the Above URL, I need to get the value for the parameter: AccountName. Here is how it got achieved using javascript:

function getEID()
{
	loc=window.location.href;
	var AccNameIndex=loc.indexOf("accountname");
	var TempAccountName=loc.substring(AccNameIndex+12);
	var AmpLoc=loc.indexOf("&");

	if(AmpLoc==-1)
	{
		AccountName=TempAccountName;
	}
	else
	{
		AccountName=loc.substring(AccNameIndex+12,AmpLoc);
	}

	i=AccountName.indexOf("\\");
	Eid=AccountName.substring(i+1);
	alert(Eid);
}

Another Case:

Today, I am running in a situation like: I have to get the value from URL and set that value to SharePoint form’s field.

My URL is: http://abc.com/sites/xyz/Lists/Metrics/Edit.aspx?List=3f7f4d96%2D00da%2D46f9%2Dae38%2D5053a9e8b321&ID=319&Source=http%3A%2F%2Fabc.com%2Fsites%2Fxyz%2FOwnerEntry%2Easpx%3FProjectID%3D71

from the above I have to extract ProjectId value and set to SharePoint List Forms value.

Get Query String from the URL and Set the Form field

Here is how I have done that with JavaScript.

After the section: <asp:Content id=”Content1″ runat=”Server”contentplaceholderid=”PlaceHolderMain”>, Paste the below code:

<script type="text/javascript">

_spBodyOnLoadFunctionNames.push("getQueryParam('ProjectID')");

function getQueryParam(parameter) {
	var loc = location.search.substring(1, location.search.length);
	var param_value = false;
	var params = loc.split("%3F");
	for (i=0; i<params.length;i++) 
	{
		param_name = params[i].substring(0,params[i].indexOf('%3D'));
		if (param_name == parameter) 
		{
			param_value = params[i].substring(params[i].indexOf('%3D')+3)
		}
	}

	if (param_value) 
	{
		document.getElementById('ctl00_PlaceHolderMain_g_602ee269_6f0c_4cb2_8bb1_740b17695b21_ff2_1_ctl00_ctl00_TextField').focus();
		document.getElementById('ctl00_PlaceHolderMain_g_602ee269_6f0c_4cb2_8bb1_740b17695b21_ff1_1_ctl00_ctl00_TextField').blur();
		document.getElementById('ctl00_PlaceHolderMain_g_602ee269_6f0c_4cb2_8bb1_740b17695b21_ff1_1_ctl00_ctl00_TextField').innerText = param_value;
		document.getElementById('ctl00_PlaceHolderMain_g_602ee269_6f0c_4cb2_8bb1_740b17695b21_ff1_1_ctl00_ctl00_TextField').readOnly=-1;
		document.getElementById('ctl00_PlaceHolderMain_g_602ee269_6f0c_4cb2_8bb1_740b17695b21_ff1_1_ctl00_ctl00_TextField').className="Read-Only";
	}
}
</script>

<style type="text/css">
.Hidden-Element {
	display:none;
}
.Read-Only {
BACKGROUND-COLOR: #f0f5f7
}
</style>

Salaudeen Rajack

Information Technology Professional with Two decades of SharePoint Experience.

One thought on “How to Get the Query String from the URL and Set the Form field value?

  • August 14, 2015 at 9:11 PM

    Thanks for this article,

    What if I have multiple parameters?

    Reply

Leave a Reply