Getting query values from url's are crucial data transferring methods for webmasters. Despite there are many efficient ways of getting query values from server side (asp.net, php, ...), sometimes we still need to get query values from client side (like javascript).
In the following example, we will try to get 1 or more query values with Javascript/Jquery.
Get Query Value With Javascript/Jquery
Our script block:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var qs = (function (a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i) {
var p = a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
</script>
<script>
$(document).ready(function () {
$("#queryValue").text(qs["q"]);
});
</script>
And html block:
<div>
your query value is <span id="queryValue"></span>
</div>
And the output will be like:
Get More Than 1 Query Values With Javascript/Jquery
Ok, sometimes we need to get more than 1 query value. For example, if we need to get day, month and year data of a datetime seperately with queries:
Our script block:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var qs = (function (a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i) {
var p = a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
</script>
<script>
$(document).ready(function () {
$("#day").text(qs["day"]);
$("#month").text(qs["month"]);
$("#year").text(qs["year"]);
});
</script>
And our html block:
<div>
Day: <span id="day"></span><br />
Month: <span id="month"></span><br />
Year: <span id="year"></span>
</div>
Finally, our output will be like this: