Today, while working on my project I needed to get query string parameter’s value.
Here I would like to share a javascript code snippet that returns an object with querystring parameter and respective value.
JavaScript function that returns key/value pairs object:
Let’s assume we have following URL:
http://localhost/testpage.aspx?param1=value1¶m2=value2
Code to get Object of querystring parameter’s value:
Code to get parameter value by its name:
Here I would like to share a javascript code snippet that returns an object with querystring parameter and respective value.
JavaScript function that returns key/value pairs object:
function GetQueryStringParameters(){
var qstring = window.location.search.replace('?', '').split('&');
var qObj = {};
for (var i = 0; i < qstring.length; i++) {
var parametername = qstring[i].split('=')[0];
var parametervalue = qstring[i].split('=')[1];
qObj[parametername] = parametervalue;
}
return qObj;
}
Example:
Let’s assume we have following URL:
http://localhost/testpage.aspx?param1=value1¶m2=value2
Code to get Object of querystring parameter’s value:
$(document).ready(function(){
var qparams = GetQueryStringParameters(); // fetch all parameters with their values.
if (qparams["param1"]){
alert("param1:- " + qparams["param1"]);
}
if (qparams["param2"]){
alert("param2:- " + qparams["param2"]);
}
});
Code to get parameter value by its name:
$(document).ready(function(){
alert("param1:- " + GetQueryStringParameters()["param1"] + "\t\n" + "param2:- " + GetQueryStringParameters()["param2"]);
});
Try demo below, - Click here to execute first code snippet
- Click here to execute second code snippet
Nice job dude :)
ReplyDelete