Wednesday, November 14, 2007

window.location.search Property

window.location.search Property

One of the not so commonly-used properties of window.location object in javascript is the window.location.searchproperty.

For example, in a web address like

http://www.my.org/pg.htm?user=2&role=admin

the window.location.search property will have all the characters after the "?" including it(?user=2&role=admin).
How can this information be useful? Well, for starter, we can access all the request parameters at client-side (using javascript) instead of processing it at server-side using codebehind. Since we have access to the request parameters,
we can do manipulations on its value or use the values contained in the request parameters to populate the value of the controls on the current page. For example, we have a web address like:

http://www.sample.org/login.htm?username=gotwald
if login.html contains usename and password input textboxes, we can automatically populate the username field with the value from the request parameters. See the screenshot below:
Here's the complete source of the sample:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<title>Untitled Page</title>
<script type="text/javascript">
window.onload = function()
{
if(window.location != null && window.location.search.length > 1 )
{
var urlParameters = window.location.search.substring(1);
var
parameterPair = urlParameters.split('&');
var
pos = parameterPair[0].indexOf('=');
var
argName = parameterPair[0].substring(0, pos);
var
argVal = parameterPair[0].substring(pos + 1);
if
(argName == 'username' )
{
document.getElementById('user').innerText = argVal;
}
}
}
</script>
</head>
<body>
<table cellpadding="4" cellspacing="0">
<
tr>
<td colspan="2">Enter login information</td>
</tr>
<tr>
<
td align="right">username:</td>
<td><input type="text" size="25" id="user" name="user" /></td>
</tr>
<
tr>
<
td align="right">password:</td><td><input type="text" size="25" id="pass" name="pass" /></td>
</tr>
lt;tr>
<td align="right"></td>
<td><input type="button" value="login" /></td>
</tr>
</table>
</
body>
</html>

Still you need to add input validation and error-handling in your code should you
need to adopt this sample code but the code itself is running on a "happy scenario",
if you know what I mean.

1 comment:

Anonymous said...

Code colorizer sucks. Still looking for a better one.