user2839497 user2839497 - 4 years ago 252
Javascript Question

How to access variable passed in a query string into document.ready function of jQuery?

I'm loading a page with URL as follows :


I tried following code to access the value of a variable event_id as follows :

$(document).ready(function() {

var query_event_id = $.url().param('event_id');

But no success. Can somebody please help me in accessing the value passed in a query string?


Answer Source

You need a function to get the appropriate info from the query string.

There is a good one in this thread: How can I get query string values in JavaScript?

Applying that to your situation you can do the following:

function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
      results = regex.exec(;
  return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

var query_event_id = getParameterByName('event_id');

By checking if the query_event_id value evaluates to something truthy, you avoid taking any action if the query string is not present.

Also, if you include your JavaScript at the bottom of the page, before the closing </body> tag, you can avoid the call to $(document).ready(...);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download