Thursday, December 17, 2009

Using Javascript to Read Query string

I was kind of having an interesting problem today when trying to build something for my company PerfectForms.

I was building a form and I need to dynamically read the queryString and pass it to the embedded script which creates the form at runtime.

I was trying couple of things and searched online, nothing really kind of gave me a complete solution (Well, my lazy butt was expecting a complete solution). So I kind of placed it together from different articles which actually works.

I am placing it here in case someone needs it.


function GetParamValue(paramID){
var strToRead = window.location.search;
//Returns the URL including the query
string.paramID= paramID.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + paramID + "=([^&#]*)";
var regex = new RegExp(regexS);
if (typeof (strToRead) == 'undefined') strToRead= window.location.href;
var paramValue = regex.exec(strToRead);
if (results == null)
return "";
else
return paramValue[1];
}

now you can call the above funtion by passing in the URL.

To get the URL use window.location.search

You can use: < input type="text" value="" id="xyz" />
< input onclick="javascript:GetParamValue('qqq');" value="Read Param Values" type="button" >
Hope this helps.

No comments:

Post a Comment