Saturday, 21 May 2011

Parsing the query string in Javascript into a single GLOBAL object


Two useful ideas combined:

1. From the book "Javascript the good bits", comes the idea to put all your (Javascript) global variables as ?? of a single global object called GLOBAL like this

var GLOBAL={}
GLOBAL.v1="value1";
GLOBAL.v2=0xFF;

2. If the html document is called with a URL with a search string (file.htm?v1=value1&v2=0xFF) then using Javascript you can parse the query string in the following way...

// http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
// load GLOBAL with properties from the querystring at the end of the URL
// e.g. "?session=2010_2011&mod_id=COA122" produces GLOBAL.session='2010_2011' & GLOBAL.mod_id='COA122'

var GLOBAL={}

location.search.replace(
  new RegExp("([^?=&]+)(=([^&]*))?", "g"),
  function($0, $1, $2, $3) {
    var e="GLOBAL."+$1+" = '"+$3+"'"; 
    //alert(e); 
    eval(e);
  }
);

Thursday, 12 May 2011

Removing rowspan from a table

I had written a data mining (scraping) script to obtain data from a table and it was working - until the table started having rowspan entries in it. I decided the easiest way to continue was to write a script to replace the rowspan entries with the requisite number of simple entries.

Here is the rowspan replacement script I used (it is written in Javascript and uses jQuery)
The reverse() bit is needed to preserve order - the script uses prepend to insert new elements so we have to start with the last element that needs work and finish with the first.


function replace_rowspan(section){
$.fn.reverse = [].reverse; //http://forum.jquery.com/topic/jquery-reverse-a-collection-of-jquery-elements
//script to process an array containing rowspan and re-write it without rowspan by putting in all the repeats
while($(section).find("td[rowspan]").length>0){ //are there any rowspans left
$(section).find("tr>td[rowspan]:first").each(function(i,tdi){ //find a row with a rowspan
var the_row=$(tdi).parents("tr");
$(the_row).find("td[rowspan]").reverse().each(function(j,tdj){
var c=$(tdj).clone();
var rs=$(tdj).attr("rowspan")-1;
var v=$(tdj).text();
$(tdj).removeAttr("rowspan");
if(rs>=2) //if the rowspan left is 2 or more, then leave the rowspan attribute in and let it be processed next time round
$(the_row).next().prepend($(c).attr("rowspan",rs).addClass("green") );
else if(rs==1) // otherwise this will be the last new entry and the rowspan attribute can be removed
$(the_row).next().prepend($(c).removeAttr("rowspan").addClass("red") );
})
})
}
}