Monday, March 27, 2006

Make Any HTML Form Print Friendly With JavaScript

 
The following code snipet loops over all the form elements looking for "text" form inputs and converts them into wrapping DIV tags.  This browser-based transformation makes printable confirmation pages easy to generate on the server using the same HTML form generation techniques that are used to display the data in an edit-ready format.
 
 
 
var replaced = 0;    
var reDigit = /^\s*\d*\s*$/;
for (var i=0; i < this.document.forms[0].elements.length; i++) {
     if( document.forms[0].elements[i].type == "text" ) {
          var text = this.document.forms[0].elements[i].value;
          if( text == "" ) {
               var newP = document.createElement("p");
               newP.style.fontFamily = "Arial, Verdana, Helvetica, sans-serif";
               newP.style.fontSize = ".90em";
               var txtNode = document.createTextNode("--");
               newP.appendChild(txtNode);
               document.getElementById(document.forms [0].elements[i].id).parentElement.appendChild(newP);
               document.getElementById(document.forms[0].elements[i].id).style.display='none';
          } else {
               var newP = document.createElement ("div");
               newP.style.fontFamily = "Arial, Verdana, Helvetica, sans-serif";
               newP.style.fontSize = ".90em";

               if( this.document.forms[0].elements[i].value.search(reDigit) == -1 ) {
                    newP.style.border = "solid black 1px";
                    newP.style.width = "179px";
                    newP.style.padding = "2px";
                }
               var txtNode = document.createTextNode(text);
               newP.appendChild(txtNode);
               document.getElementById(document.forms[0].elements[i].id).parentElement.appendChild(newP);
               document.getElementById (document.forms[0].elements[i].id).style.display='none';
          }
    }

No comments: