I would like to know whether there is a jQuery function which can check whether a variable in the URL is set.
Something similar to the isset() function in PHP
Th
jQuery does not provide such methods. But you don’t even need jQuery to do so:
(function() {
var params = null;
this.l = typeof Location !== "undefined" ? Location.prototype : window.location;
this.l.getParameter = function(name) {
return Array.prototype.slice.apply(this.getParameterValues(name))[0];
};
this.l.getParameterMap = function() {
if (params === null) {
params = {};
this.search.substr(1).split("&").map(function(param) {
if (param.length === 0) return;
var parts = param.split("=", 2).map(decodeURIComponent);
if (!params.hasOwnProperty(parts[0])) params[parts[0]] = [];
params[parts[0]].push(parts.length == 2 ? parts[1] : null);
});
}
return params;
};
this.l.getParameterNames = function() {
var map = this.getParameterMap(), names = [];
for (var name in map) {
if (map.hasOwnProperty(name)) names.push(name);
}
return names;
};
this.l.getParameterValues = function(name) {
return this.getParameterMap()[name];
};
})();
This extends the location object with the methods getParameter, getParameterMap, getParameterNames, and getParameterValues (similar to Java’s ServeletRequest) that can be used as follows:
if (typeof location.getParameter("foo") !== "undefined") {
// foo parameter exists
}
The return values of getParameter have the following meaning:
undefined: given parameter not presentnull: given parameter has no assigned value (e.g. foo in a=b&foo&c=d)