4

I have the following:

$(document).ready(function() {
window.location.href='http://target.SchoolID/set?text=';
});

So if someone comes to a page with the above mentioned code using a url like:

Somepage.php?id=abc123

I want the text variable in the ready function to read: abc123

Any ideas?

Strong Like Bull
  • 11,155
  • 36
  • 98
  • 169

3 Answers3

4

you don't need jQuery. you can do this with plain JS

function getParameterByName( name ) //courtesy Artem
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

and then you can just get the querystring value like this:

alert(getParameterByName('text'));

also look here for other ways and plugins: How can I get query string values in JavaScript?

Community
  • 1
  • 1
Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
  • Added another answer. If you feel like it update your answer and i will delete mine. Thanks for the helpful code. – ojblass Jun 02 '15 at 19:49
3

check out the answer to this questions: How can I get query string values in JavaScript?

that'll give you the value of the id parameter from the query string.

then you can just do something like:

$(document).ready(function() {
    var theId = getParameterByName( id)
    var newPath = 'http://target.SchoolID/set?text=' + theId
    window.location.href=newPath;
});
Community
  • 1
  • 1
Patricia
  • 7,752
  • 4
  • 37
  • 70
0

To help people coming after me that want to have multiple variables and to enhance Moin's answer here is the code for multiple variables:

function getParameterByName( name ) //courtesy Artem
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
  {
    if ((results[1].indexOf('?'))>0)
        return decodeURIComponent(results[1].substring(0,results[1].indexOf('?')).replace(/\+/g, " "));
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}
ojblass
  • 21,146
  • 22
  • 83
  • 132