[thelist] JavaScript and GET name value pairs

Chris Blessing webguy at mail.rit.edu
Wed Dec 18 12:00:03 CST 2002


Tom-

May I suggest you alter your form slightly?

<form method="get" name="test" action="getVars.html">
<input type="hidden" name="food" value="eggs">
<input type="hidden" name="drink" value="beer">
<input type="submit" value="submit">
</form>

You could probably use the other form, but this is much more, eh, "normal".
;^)

Anywho, you can access these values using the location.search property.  Check it out:

// this will be "?food=eggs&drink=beer"
var yourQS = location.search;

// now you need to eliminate that ? mark
yourQS = location.search.substring(1);

// now we'll setup the array of name/value pairs
// by splitting them via the & character
// note: this results in each array element being a
// name=value string, so pairs(0) = "food=eggs"
var pairs = yourQS.split("&");

// now you can loop through the array and split again!
var tmpAry;
for(var i=0; i<pairs.length; i++){
	tmpAry = pairs(i).split("=");
	alert(tmpAry(0)); // the name
	alert(tmpAry(1)); // the value for said name
}

HTH!  BTW this is a slight adaptation of the code found on pg. 245 of "JavaScript: The Definitive Guide" 3rd edition (yeah I'm out of date).

Chris Blessing
webguy at mail.rit.edu
http://www.330i.net

> I have a need to pull some GET name/value pairs using JS (long story,
> I have no choice). I've been struggling with some code I found on the
> net and wondered if anyone here has done this.
>
> The first thing is I have a test page that sends the get variables.
> It is simply this form:
>
> <form method="get" name="test"
> action="getVars.html?food=eggs&drink=beer">
> <input type="submit" value="submit">
> </form>
>
> Then the code I found does a few things, first it pulls the location
> to get the whole string like this:
>
> query = this.location.href;
>
> This gives me:
>
> file:///C:/getVars.html?
>
> Notice, this has NOT grabbed the GET variables in the string..anyone
> know why? Does anyone have a good script for doing this? What I have
> found on the net has been wanting or old.
>
> TIA
>
> Tom
>




More information about the thelist mailing list