Wise ASP Logo Surfer's Choice Member
   

Wise ASP - The JScript Enumerator and the HTML Form Collection

Looping Through a HTML Form Collection

Collections implement a very useful feature that makes it easy to get all the values from them. Each value is accessed using a unique string key. There is no concept of a numeric index to each value. So it's difficult to iterate through all the values in a collection using a traditional loop. We can, however, use the JScript Enumerator object to iterate through the collection.

  When the method attribute of a form is POST, the data comes wrapped up in the HTTP header. The values from the controls are placed in the Request object's Form collection.

function showCollection() { 
  var items = new Enumerator(Request.Form); 
  debug("<table>"); 
  while(!items.atEnd()) { 
    i = items.item(); 
    debug("<tr>"); 
    debug("<td>Control name <b>" + i + "</b></td>"); 
    debug("<td> has the value <b>" + Request.Form(i) + "</b></TD> "); 
    items.moveNext(); 
  } 
  debug("</table> "); 
} 
 
function debug(str) 
{ 
  Response.write("<PRE><FONT COLOR=BLUE>" + str + "</FONT></PRE><P>"); 
} 
 
  I include the two preceding paragraphs in all of my ASP pages as a debugging tool in my development process.

The showCollections() function uses the Enumerator object to setup the collection. Next, the while block is combined with atEnd() method to determine when we reach the end of the collection. The last statement in the while block is the moveNext() method, which steps through each item in the collection one value at a time.

  Okay, now let us look in the heart of the while block. What we use here is a custom function to easily turn Response.Write on and off. The debug() function is an easy way to turn on and off any write statements while you are testing. showCollections() will call debug(), which expects a string and then "Response.Write()" it to the screen. When you are finished developing, simply comment the only line of code in debug() and you will no longer have any of your debug() statements displayed in your web page. All debug() statements are now controlled from one point.

88x31cardsvisoranm