Search code examples
javascriptjqueryhref

Read utm query string using jQuery


I am trying to read url parameters like the following:

http://www.someoneswebsite.com/?utm_source=twitter&utm_medium=twit&utm_campaign=randomtwitter
http://www.someoneswebsite.com/?utm_source=twitter&utm_medium=twit&utm_campaign=randomtwitter1

On my page, I have a hidden field like this:

<input type="hidden" name="hiddenVal" value="old value" />

I want to access utm_campaign and check if it contains the string "randomtwitter". If it does, change the value of the hidden field.

Here's what I have come up with:

var query = window.location.search;

if( query.indexOf('utm_campaign=randomtwitter') !== -1 ) {
     $('#hiddenVal').val('new value');
}

But it doesn't work. Where am I going wrong?


Solution

  • Use .href instead to get the location link :

    var query = window.location.href;
    

    Hope this helps.