Okay. Say you have a javascript variable you want to pass through a URL. How do you read that variable back into your javascript?
http://domain/folder/index.html?variable=3
location.search is the stuff after the question mark (it was defined that way so you wouldn’t have to look for the question mark yourself)
So if “variable” (8 characters long) is the name of your, um, variable,
then you can grab the value like this:
varvalue = document.location.search.substring(10)
The substring starts after the equal sign and goes to the end of the string. This method won’t work if somebody types the url and makes a mistake when typing “variable,” but if the URL is passed by a GET from a form that you designed, or through a link, etc… then this will work.
Tagged As Javascript
Comments are Open (4)
Posted at 12:00 PM
Comments
Garby O'Dill
What the heck are you talking about? How does this work?
Posted by: Garby O'Dill | August 6, 2003 12:24 PM
Tony
What this means is that you can read a variable into your page through Javascript from a previous page.
Example: you have a form. You want the second page of the form to be prefill on some of the items based upon previous answers. If you pass those form answers in a URL string, you can read them in and use them.
The substring(10) relates to the cursor position that Javascript is looking for. I'm using 10 places because there are 10 characters after the = sign. Then it will grab that variable and use it.
It's not perfect, as if you have multiple variables you're passing, then you'll either have to GREP the &'s and determine the length, or do something else. (of which I'm sure that there are numerous ways).
This was just based upon a simple problem I was having trying to pass a single variable and have that read into Javascript.
Posted by: Tony | August 6, 2003 05:56 PM
Matt
Very cool. Thanks!
Posted by: Matt | September 12, 2003 05:05 PM
John Towers
Just came across this, incase anyone is still interested. I think it is a bit cleaner:
http://www.cybertechhelp.com/html/tutorials/tutorial.php/id/48
Posted by: John Towers | May 6, 2004 04:06 PM