Wednesday
Apr 15, 2009
6:30 am
Hashtables and form labels with jQuery forms
Javascript implements hash tables in a limited and somewhat unwieldy fashion as associative arrays. The jQuery.field plugin has some useful functions including a formHash() function that returns all the elements of the form with the field ids as the hash keys and the form values as the hash values corresponding to those keys.
Some people consider treating associative arrays as hash tables as being downright bad since they appear to have all the characteristics one would expect, but in fact, do not. For example, the way one iterates over the array and the ability to determine the size of the array (array.length).
This custom implementation solves those problems rather handily (and there’s an implentation in the comments with the Ajaxian post linked in the previous paragraph). I believe this is what people refer to when they recommend using objects rather than simple associative arrays (since arrays are, themselves, objects in Javascript).
For the purposes of the work I was doing, where it’s not intended for production and where performance (or scalability) is not a consideration, but rapid prototyping and the ability to easily correlate form fields with labels, this implementation seems to work just fine:
jQuery.fn.labelList = function(){ var strValueList = []; var label = $(this).find("label"); label.each( function (index) { var id = $(this).attr('for') || 'undefined'; if (id) { labelText = $(this).text(); if (labelText.substr(0,1)=="*") { labelText = labelText.substring(1, labelText.length); } if (labelText.substr(labelText.length-1,1) == ":") { labelText= labelText.substring(0, labelText.length-1); } strValueList[id] = labelText; } }); return( strValueList ); }
Which is then used in a function something like the following which is called using:
$("#yourFormID").collectResults(); jQuery.fn.collectResults = function(){ var currentForm = ""; var myResults=$(this).formHash(); var myLabelresults=$(this).labelList(); currentForm += " <ul>"; $.each(myResults, function(i,item) { itemName = myLabelresults[i]; if(itemName != undefined && itemName != "") { currentForm += " <li>"+ itemName + ": " + item + "</li> \n"; } } ); currentForm += "</ul> "; $("#outputContainerID").append(currentForm); }