Requirement: Get Current Page Parameter Using Javascript
In This blog I explained you How to Get Current Page Parameter Using Javascript.
There is no predefined function in javascript to get current page parameter so here we need to write our own function .
So here are the steps one should follow to Get Current Page Parameter Using Javascript
- Get the current page url using : window.location.href;
- Pass the url to the function we write to get the parameter . This function returns the parameter we need .
here is the code for javascript function
<script>
var url = window.location.href;
// this is our javascript function code to get url paramater
function getAllUrlParams(url)
{
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i=0; i<arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// in case params look like: list[]=thing1&list[]=thing2
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1,-1);
return '';
});
// set parameter value (use 'true' if empty)
var paramValue = typeof(a[1])==='undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();
// if parameter name already exists
if (obj[paramName]) {
// convert value to array (if still string)
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
// if no array index number specified...
if (typeof paramNum === 'undefined') {
// put the value on the end of the array
obj[paramName].push(paramValue);
}
// if array index number specified...
else {
// put the value at that index number
obj[paramName][paramNum] = paramValue;
}
}
// if param name doesn't exist yet, set it
else {
obj[paramName] = paramValue;
}
}
}
return obj;
}
</script>
Now get your page parameter by simply writing parameter name after function name followed by dot operator
for example:
here stuid is the name of param in url
var param = getAllUrlParams().stuid;
console.log(‘value of parameter stuid is’,param );
Now you can get any parameter by simply calling this function in your script
Hits: 489
Well explained
thanks for your appreciation