Friday 3 June 2011

Generic jQuery method to attach a querystring value to all the links in a page

Ever wondered how to attach a querystring, which exist in the original request, to all the requests made by hypertext link (<a> tag) clicks in an ASPX page. See below script.

$(document).ready(function () {
$('a').click(function (event) {

var $a = $(this);

//Add quesrystring if it is a relative URL and the querystring is not part of the href value already
var appendqstring = $a.attr("href").toLowerCase().indexOf("http://") == -1 && $a.attr("href").toLowerCase().indexOf("https://") == -1 &&
$a.attr("href").toLowerCase().indexOf(".aspx") != -1 && $a.attr("href").toLowerCase().indexOf("qs=") == -1;

if (appendqstring ) {
event.preventDefault();
location.href = $a.attr("href") + "?qs=" + GetQStringVal("qs");
}
});
});

/* function to read value of the given key, x, from querystring */
function GetQStringVal(x) {
var a = location.search.substring(1); var b = a.split("&");
for (var i = 0; i < b.length; i++) {
var c = b[i].split("=");
if (c[0].toLowerCase() == x.toLowerCase()) { return c[1]; }
}
return "";
}

No comments:

Post a Comment