Sunday 22 January 2017

Fetching Parameters value from URL using Java Script

How to get parameter's value  from URL using jquery ?

Some of the time we are in need to fetch the parameters which are in URL so that we can make query  or use them as per our logic.So we can easily fetch URL  parameters by following code with ease.

1) Let say our URL is    http://localhost:8080/DemoApp/fetchParam.action?id=9&monthYear=2017-          22    and we want to fetch value of id and monthYear in current view page for any xy logic. I              have  made one function  by the name of getUrlParameter ('key')   where key will be the                  parameter name in URL like in this example  id and monthYear will act as key and than we can          do some   manipulation by getting the URL and make use of these values in current page as and          when required.

        var idValue= getUrlParameter('id');
        var monthYearValue = getUrlParameter('monthYear');

Note: idValue and  monthYearVal   can be used in current page for further use.


2) Function definition is as follows for same:
 
function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}


This function  will return  value according to the key passed.So this we can fetch query string parameters from URL with ease.


Thanks for reading
Regards
Anoop Butola





No comments:

Post a Comment