How can I get the url parameter in jquery ready function?

I have the following:

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

So, if someone comes to the page with the above code using the URL, for example:

Somepage.php? ID = ab123

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

Any ideas?

+3
source share
3 answers

you don't need jQuery. you can do it with simple 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'));

See also other ways and plugins here: How to get query string values ​​in JavaScript?

+3
source

check answers to the following questions: How to get query string values ​​in JavaScript?

which will give you the id parameter value 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; }); 
+3
source

To help people following me who want to have several variables and improve Moin, here is the code for several 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, " ")); } } 
0
source

Source: https://habr.com/ru/post/1483198/


All Articles