code.nontalk.com

Code snippets for C#, T-SQL and JavaScript

Thursday, October 19, 2006

Read/Modify Querystring Variables with Javascript

There are a lot of nice little javascripts out there which allow you to easily read values from the query string, but I wanted a script that would allow you to easily read and modify querystring values. I created the following script which relies on the Prototype library (version 1.5.0_rc0):

/*--------------------------------------------------------------------------*/
/*  QueryString Object
*  (c) 2006 Jesse Gavin http://code.nontalk.com/
*
*  Depends upon:
*  - Prototype JavaScript framework, version 1.5.0_rc0
*    (c) 2005 Sam Stephenson <sam@conio.net>
*
*  This script is freely distributable under the terms of an MIT-style license.
*  For details, see: http://code.nontalk.com/
*
/*--------------------------------------------------------------------------*/

var QueryString = {
   params : $H(window.location.search.toQueryParams()),
  
   get : function(key, defaultValue) {
       if (defaultValue == null) defaultValue = null;
       var value = this.params[key]
       if (value==null) value = defaultValue;
       return value;
   },
  
   set : function(key, value) {
       this.params[key] = value;
   },
  
   remove : function(key) {
       this.params = this.params.collect(function(param) {
           if (key != param.key) return param;
       }).compact();
   },
  
   make : function() {
       return "?" + this.params.collect(function(param) {
           return escape(param.key) +"="+ escape(param.value);
       }).join("&");
   },
  
   go : function() {
       window.location.href = location.pathname + this.make();
   }
}

Download QueryString.js

P.S. I got the idea for this from a CodeProject article written by Uwe Keim. He created a C# class to manage QueryString variables, which does all this and more on the server side.

Labels: