Geeks With Blogs
Bunch's Blog One day I'll have a catchy subtitle, one day

Using a JavaScript function to show another window from an aspx page is pretty common. Often times you need to pass some variables by appending them to the URL string. And sometimes you don’t know which variables you may or may not need. This example shows one way of passing the variable(s) you need.

The code below is going to pass some or all of the variables to a page that displays a map. The user may know some of the follow information about the site they are trying to find on the map like the zip code, the actual X/Y coordinates or the ID of the site. This function can handle any combination of those items and create the proper URL.

 function ShowLocation()
    var locURL = 'http://servername/locationapp/default.aspx';
    var windowName = 'LocationPage';
    var siteID = document.forms[0].txtSiteID.value;
    var zip = document.forms[0].txtZip.value;
    var X = document.forms[0].txtX.value;
    var Y = document.forms[0].txtY.value;
    locURL += '?';
    if (siteID!=0)
        locURL += 'siteID=' + siteID + '&';
    if (zip!=0)
        locURL += 'zip=' + zip + '&';
    if (X!=0)
        locURL += 'X=' + X + '&';

    if (Y!=0)
        locURL += 'Y=' + Y + '&';


    var urlLen = locURL.length;
    var lastChar = locURL.charAt(urlLen - 1);
    if (lastChar == '&')
        locURL = locURL.slice(0, urlLen - 1);

    window.showModalDialog(locURL,null, 'dialogWidth=500Px;dialogHeight=500Px;');
    return false;

By checking the values of the various variables and adding only those that are not 0 you can build up the URL string with just the ones you want. The trick to clean off the last ampersand is the slice function. Now the URL is cleaned up ready for the locationapp to handle.

Technorati Tags: ,
Posted on Monday, September 20, 2010 2:20 PM | Back to top

Comments on this post: URL Parameter Cleanup in JavaScript

# re: URL Parameter Cleanup in JavaScript
Requesting Gravatar...
Have you checked out jquery's $.params(obj) method? You could build a parameter object and then let jquery do the serialization.
Left by Ryan on Sep 20, 2010 5:33 PM

Your comment:
 (will show your gravatar)

Copyright © Bunch | Powered by: