[thelist] Javascript Brain *fluff

Ben Henick persist1 at io.com
Thu Feb 20 10:03:01 CST 2003


On Thu, 20 Feb 2003, Rob Smith wrote:

> Hey,
>
> Is there a way to get the query string variables with Javascript?

If you're just looking to get the variables rather than create an object
that ultimately talk to a database...


a = window.location.search.substring(1);
b = a.split("&");

/* Unless you have an obscene (more than, say, six or eight) quantity of
name-value pairs on that URL, there's probably little harm in: */

for (i = 0; i < b.length; i++)
{
  eval(b[i]);
}

/* But if that makes you uncomfortable...: */

c = new Array();
d = new String();
e = new Array();

for (i = 0; i < b.length; i++)
{
  c = b[i].split("=");
  d = c[0];
  e[d] = c[1];
}

/*  Which creates an associative array to the effect of
CGIArray["varname"] = foo; */

Be careful for type mismatches.

Relevant objects:

'search' property of Location object
'split' method of Array object

See also:

'toString' method of Number object (used for both ints and floats in JS)

<tip type="Typing Issue in JavaScript regarding forms" author="Ben
Henick">

Something else, for the newbies reading... when dealing with values of
fields in a form, you'll discover that they're all typed as strings.  If
you're looking to do any sort of math on numbers the user may be supplying
in this form, you get a lot of 'NaN' results even though the values
supplied are clearly numbers...

You fix that by subtracting zero.

Suppose you have a form for which a number has been supplied as a field
value, e.g.

document.forms[0].elements["ItemOnePrice"].value = "100";

At least, that's what the interpreter sees.

If OTOH you do:

a = (document.forms[0].elements["ItemOnePrice"].value - 0);

and reference the variable 'a' in your math instead of the value of the
form element, you'll be in good shape.

</tip>


HTH
--
Ben Henick                     "In the long run, men hit only what they aim
Web Author At-Large             at.  Therefore, though they should fail
http://www.io.com/persist1/     immediately, they had better aim high."
persist1 at io.com                 -- Henry David Thoreau





More information about the thelist mailing list